Stop a Stream of Data Before End Of File
In my Silverlight application I need to download large files. I am currently streaming this data from a byte array by calling an ASPX page on the same server hosting the Silverlight app. The ASPX Page_Load()
method looks like this:
protected void Page_Load(object sender, EventArgs e)
{
// we are sending binary data, not HTML/CSS, so clear the page headers
Response.Clear();
Response.ContentType = "Application/xod";
string filePath = Request["file"]; // passed in from Silverlight app
// ...
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// send data 30 KB at a time
Byte[] t = new Byte[30 * 1024];
int bytesRead = 0;
bytesRead = fs.Read(t, 0, t.Length);
Response.BufferOutput = false;
int totalBytesSent = 0;
Debug.WriteLine("Commence streaming...");
while (bytesRead > 0)
{
// wr开发者_JAVA百科ite bytes to the response stream
Response.BinaryWrite(t);
// write to output how many bytes have been sent
totalBytesSent += bytesRead;
Debug.WriteLine("Server sent total " + totalBytesSent + " bytes.");
// read next bytes
bytesRead = fs.Read(t, 0, t.Length);
}
}
Debug.WriteLine("Done.");
// ensure all bytes have been sent and stop execution
Response.End();
}
From the Silverlight app, I just hand off the uri to object that reads in the byte array:
Uri uri = new Uri("https://localhost:44300/TestDir/StreamDoc.aspx?file=" + path);
My question is... How do I stop this stream if the user cancels out? As it is now, if the user selects another file to download, the new stream will start and the previous one will continue to stream until it has completed.
I can't find a way to abort the stream once its been started.
Any help is greatly appriciated.
-Scott
If you are sure it's only going to be 30K of data, you might consider simplifying it with File.ReadAllBytes.
If you abort the request on the client, using HttpWebRequest.Abort
(like in this answer) then a ThreadAbortException
should get raised on the server in response to the end of the TCP connection, which will stop that thread writing out data.
I just hand off the uri to object that reads in the byte array
I'll assume for the moment you are simply using the WebClient
. The WebClient
has a CancelAsync
method. The eventargs of OpenReadCompleted
has a Cancelled
property you can test.
When the client aborts a connection the server will not send any more bytes but server code will continue to run, its the internals of IIS which will simply discard the buffers it receives since it no longer has anywhere to send them.
On the server you can use the IsClientConnected
property of the HttpResponse
object to determine whether to abort your pump loop.
BTW, You really should consider moving this code to a .ashx, an .aspx carries a lot of baggage that you don't need.
精彩评论