views:

199

answers:

2

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?

+1  A: 

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...

Foxfire
+1: it's an idea, I'll try
Rubens Farias
A: 

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.

Rubens Farias