Home All Groups Group Topic Archive Search About

Streaming without CPU occupying?

Author
17 Dec 2005 10:33 AM
the friendly display name
Following problem:

I want to stream a file to the client, but the logic takes too much CPU time
(100% in fact..) this is the code:



public class Download : System.Web.UI.Page

{

   private byte[] buffer;
   private AsyncCallback callback;
   private Filestream fs;



   private void Page_Load (object sender, System.Eventargs e)

{

   fs = File.Open (....) // I won't bore you with the non interesting parts

   Response.Clear();

   Response.ClearContent();

   Response.ClearHeaders();

   Response.AddHeader("content-disposition", "attachment;
filename=blabla.exe");

   Response.ContentType = "application/octet-stream";

   fs.BeginRead(buffer, 0, 1024, callback, null);



}



void whencomplete (IAsyncResult Result)

{

   int BytesRead = fs.EndRead(Result);

   if (BytesRead > 0)
   {

         Response.BinaryWrite(buffer);

         Response.Flush();

         fs.BeginRead(buffer, 0, 1024, callback, null);

      }

      if (BytesRead == 0)
      {

         fs.Close();

         Response.Close();

         }  



in private void InitializeComponent():

{

buffer = new byte[1024];

callback = new AsyncCallback (whencomplete);

}





---

This works, but it does take the whole CPU. If I add a sleep cycle in
whencomplete:

---


   if (BytesRead > 0)
   {

         Response.BinaryWrite(buffer);

         Response.Flush();
         Thread.Sleep(100);

         fs.BeginRead(buffer, 0, 1024, callback, null);

      }
----

The CPU Utilization goes nearly to zero, but only with one running download.
I tried 3 downloads at the same time, and the CPU was again quite occupied.

What's the more effective way to stream? Is it even possible to stream,
without a high cpu utilization, since it's basicaly a .aspx site, which is
running in a loop?

AddThis Social Bookmark Button