问题
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