c# – 使用backgroundWorker下载文件
发布时间:2020-12-16 01:47:10 所属栏目:百科 来源:网络整理
导读:我创建了下载程序文件 private void btnTestDownload_Click(object sender,EventArgs e){backgroundWorker1.RunWorkerAsync();} 和工作!但 private void btnTestDownload_Click(object sender,EventArgs e){backgroundWorker1.CancelAsync();} backgroundWo
我创建了下载程序文件
private void btnTestDownload_Click(object sender,EventArgs e) { backgroundWorker1.RunWorkerAsync(); } 和工作!但 private void btnTestDownload_Click(object sender,EventArgs e) { backgroundWorker1.CancelAsync(); } backgroundWorker dos不停! 解决方法
听起来你对背景工作者的目的有完全错误的想法.如果要同步下载单个文件并取消它,则所有这些功能都内置在WebClient类中.
后台工作者是长期运行的任务,总的来说,处理器密集.例如,如果您下载的文件是一个大文本文件,并且您需要解析文本文件的每一行,则可以使用后台工作程序,例如 下载文件 WebClient Client = new WebClient(); public void TestStart() { //Handle the event for download complete Client.DownloadDataCompleted += Client_DownloadDataCompleted; //Start downloading file Client.DownloadDataAsync(new Uri("http://mywebsite.co.uk/myfile.txt")); } void Client_DownloadDataCompleted(object sender,DownloadDataCompletedEventArgs e) { //Remove handler as no longer needed Client.DownloadDataCompleted -= Client_DownloadDataCompleted; //Get the data of the file byte[] Data = e.Result; } public void TestCancel() { Client.CancelAsync(); Client.DownloadDataCompleted -= Client_DownloadDataCompleted; } 处理文件 BackgroundWorker worker = new BackgroundWorker() { WorkerSupportsCancellation = true }; //Take a stream reader (representation of a text file) and process it asyncronously public void ProcessFile(StreamReader Reader) { worker.DoWork += worker_DoWork; worker.RunWorkerAsync(Reader); } public void CancelProcessFile() { worker.CancelAsync(); } void worker_DoWork(object sender,DoWorkEventArgs e) { //Get the reader passed as an argument StreamReader Reader = e.Argument as StreamReader; if (Reader != null) { //while not at the end of the file and cancellation not pending while (Reader.Peek() != -1 && !((BackgroundWorker)sender).CancellationPending) { //Read the next line var Line = Reader.ReadLine(); //TODO: Process Line } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |