允许取消 Web 请求的线程
我正在编写一个 Web 应用程序,允许用户通过 http Web 请求下载大文件。我需要为他们提供取消请求的选项,因此我为该请求创建一个线程。但是,当下载发生时,我仍然无法触发取消事件。我做错了什么? 感谢您的任何意见!
public class downloadThread {
public 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();
}
}
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 {
public 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 thread.Abort 中止线程可能不是您想要的方式。
在 DownloadImage 方法中使用异步 Web 请求怎么样? (请参阅 http://msdn.microsoft.com/en -us/library/system.net.httpwebrequest.begingetresponse.aspx )。这样您就可以调用 Web 请求的 .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.