开发者

Bandwidth throttling for file download

I've following code to limit file download speed for an application;

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);
    }
}

As always, it works fine into my development, internal and customer QA environments, but it's throwing an exception in production environment:

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

For user, a new window opens upon download dialog:

The connection with the server was reset

Do you have any idea what's going on?


It could be that the IIS this runs on assumes that your web application hangs as it's thread is unreachable while sleeping. Then it recycles the worker thread.

You should try to simply reduce the sleep interval. 1 second seems high...


Problem was that request running for more than 90 seconds.

I'd alter that HTTP handler to implement IHttpAsyncHandler and create a background, non-blocking thread. Now everything works fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜