我試圖通過webclient下載文件,代碼如下所示。問題是,如果我連續404響應很長時間,我的服務器達到100%,查看事件日誌告訴發生堆棧溢出。這裏的「count」變量是爲了避免0個字節的文件,count440是爲404個響應。404響應遞歸webclient.download方法導致服務器達到100%
int count = 0; int count404 = 0;
public Stream DownloadFileThroughWebClient(string strFilePath)
{
try
{
if (count >= 120 || count404 >= 30)
{
count = 0;
count404 = 0;
return null;
}
System.Threading.Thread.Sleep(1000);
System.Net.WebClient wc = new System.Net.WebClient();
var v = wc.DownloadData(strFilePath);
Stream FileToSave = new MemoryStream(v);
byte[] bytes = new byte[FileToSave.Length];
int numBytesToRead = (int)FileToSave.Length;
if (numBytesToRead > 0)
{
count = 0;
count404 = 0;
return FileToSave;
}
else
{
count++;
count404 = 0;
return DownloadFileThroughWebClient(strFilePath);
}
}
catch (Exception ex)
{
count++;
count404++;
return DownloadFileThroughWebClient(strFilePath);
}
}
在此先感謝。
你應該換你的WebClient的'using'塊。 – Adam
嗨@codesparkle感謝您的回覆..我認爲它是因爲遞歸異常,我的服務器在CPU上越來越高?你給了我新的想法。 – gaurav
不處理WebClient不會像您所遇到的那樣導致堆棧溢出(這更可能是由遞歸引起的)。無論如何,這是一個好主意。爲了避免堆棧溢出,您可能需要實現* explicit *堆棧。谷歌「用迭代替換遞歸」。 – Adam