一个BackgroundWorker内取消Webclient.DownloadFile [英] Cancel a Webclient.DownloadFile within a BackgroundWorker

查看:129
本文介绍了一个BackgroundWorker内取消Webclient.DownloadFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景资料:我有过的URL列表运行的程序;每个URL是被下载一次,但在后台线程运行,以保持用户界面的响应。为了报告进度,我使用的方法DownloadFileAsync。 我的问题是,我希望能够有一个取消按钮,将立即停止下载。我的code去的线沿线的东西。

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

我不能想办法或地方插入一个循环来检查取消未决。我只是稍微了解线程,不完全理解的AutoResetEvent无论是。

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.

推荐答案

如果你使用 System.Net.WebClient ,它包含了一个 CancelAsync()方法应该为你做它。所有你应该需要的是要取消让你的按钮的单击事件可以调用该方法的具体WebClient的一个参考。

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.

这篇关于一个BackgroundWorker内取消Webclient.DownloadFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆