Threading to allow cancelling a web request
I'm writing a web app that allows users to download large files over http web request. I need to give them the option to cancel the request, so I create a thread for the request. But, while the download is happening, I still can't get the cancel event to fire. What am I doing wrong? Thanks for any input!
public class downloadThread {
publi开发者_JAVA百科c int isResume;
public void downloadImage()
{ }
}
protected void btnDownload_Click(object sender, EventArgs e)
{ var x = new downloadThread();
x.isResume = 0;
tRequest = new Thread(new ThreadStart(x.downloadImage));
tRequest.Start();
while (tRequest.IsAlive)
{
DownloadImage(); //this is where the rest request happens
} }
protected void btnCancelRequest_Click(object sender, EventArgs e)
{
if (tRequest != null && tRequest.IsAlive)
{
tRequest.Abort();
}
}
Aborting a thread with thread.Abort is maybe not the way you want to do this.
How about an asynchronous web request in your DownloadImage method instead? (See http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx ). That way you can call the web request's .Abort method rather than aborting the thread.
精彩评论