2009-10-15 48 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