2009-10-15 59 views
1

我下面的代碼限制了應用程序的文件下載速度;文件下載的帶寬限制

context.Response.Buffer = false; 
context.Response.AppendHeader("Content-Disposition", 
           "attachment;filename=" + arquivo.Nome); 
context.Response.AppendHeader("Content-Type", 
           "application/octet-stream"); 
context.Response.AppendHeader("Content-Length", 
           arquivo.Tamanho.ToString()); 

int offset = 0; 
byte[] buffer = new byte[currentRange.OptimalDownloadRate]; 

while (context.Response.IsClientConnected && offset < arquivo.Tamanho) 
{ 
    DateTime start = DateTime.Now; 
    int readCount = arquivo.GetBytes(buffer, offset, // == .ExecuteReader() 
     (int)Math.Min(arquivo.Tamanho - offset, buffer.Length)); 
    context.Response.OutputStream.Write(buffer, 0, readCount); 
    offset += readCount; 
    CacheManager.Hit(jobId, fileId.ToString(), readCount, buffer.Length, null); 

    TimeSpan elapsed = DateTime.Now - start; 
    if (elapsed.TotalMilliseconds < 1000) 
    { 
     Thread.Sleep(1000 - (int)elapsed.TotalMilliseconds); 
    } 
} 

與往常一樣,它工作正常,進入我的發展,內部及客戶QA環境,但它拋出一個異常,在生產環境中:

System.Threading.ThreadAbortException: Thread was being aborted. 
    at System.Threading.Thread.SleepInternal(Int32 millisecondsTimeout) 
    at (...).Handlers.DownloadHandler.processDownload(HttpContext context, ...) 

對於用戶,一個新的窗口,在下載對話框:

The connection with the server was reset 

你知道怎麼回事嗎?

+1

我沒有答案,但它似乎很常見:http://www.google.com/search?q=SleepInternal+threadabortexception – asveikau 2009-10-15 18:40:34

回答

1

問題是該請求運行超過90秒。

我會改變該HTTP處理程序來實現IHttpAsyncHandler並創建一個後臺非阻塞線程。現在一切正常。

1

這可能是因爲運行的IIS假定您的Web應用程序掛起,因爲線程在睡眠時無法訪問。然後它回收工作線程。

你應該儘量簡單地減少睡眠間隔。 1秒似乎很高...

+0

+1:這是一個想法,我會嘗試 – 2009-10-15 18:49:13