Cancel a Webclient.DownloadFile within a BackgroundWorker

十年热恋 提交于 2019-12-11 05:58:43

问题


Background Info: I have a program running through a list of url; each URL is to be downloaded one at a time but ran in a background thread to maintain UI responsiveness. In order to report progress, I'm using the DownloadFileAsync method. My problem is that I would like to be able to have a cancel button that would immediately end the download. My code goes something along the lines of

AutoResetEvent autoMobile = new AutoResetEvent(false);
WebClient dclient = new WebClient();

//setup event handlers... for progress, etc...

dclient.DownloadFileAsync(new Uri(egg.DownloadURL), egg.LocalFilePath);
autoMobile.WaitOne();

//end of DoWork

I cannot think of a way or place to insert a loop to check for cancellation pending. I only slightly understand threads and do not fully understand the AutoResetEvent either.


回答1:


If you're using System.Net.WebClient, it contains a CancelAsync() method which should do it for you. All you should need is a reference to the specific WebClient you want to cancel so your button's click event can call that method.

Mind you, I haven't tested this myself - but that'd be the first thing I try.



来源:https://stackoverflow.com/questions/6522244/cancel-a-webclient-downloadfile-within-a-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!