线程以允许取消 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();
                }
            }

用线程中止线程。中止可能不是您想要的方式。

在您的 DownloadImage 方法中使用异步 Web 请求怎么样?(见 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx)。这样,您就可以调用 Web 请求的 .中止方法而不是中止线程。

最新更新