.NET2.0版本中基于事件的异步编程模式(EAP)
一、引言
APM为我们实现异步编程提供了一定的支持,同时它也存在着一些明显的问题——不支持对异步操作的取消和没有提供对进度报告的功能,对于有界面的应用程序来说,进度报告和取消操作的支持也是必不可少的。
微软在.NET 2.0的时候就为我们提供了一个新的异步编程模型,也就是基于事件的异步编程模型——EAP(Event-based Asynchronous Pattern )。
二、介绍
实现了基于事件的异步模式的类将具有一个或者多个以Async为后缀的方法和对应的Completed事件,并且这些类都支持异步方法的取消、进度报告和报告结果。
当我们调用实现基于事件的异步模式的类的 XxxAsync方法时,即代表开始了一个异步操作,该方法调用完之后会使一个线程池线程去执行耗时的操作,所以当UI线程调用该方法时,当然也就不会堵塞UI线程了。
并且基于事件的异步模式是建立了APM的基础之上的,而APM又是建立了在委托之上的。
public static void GetInfomation(){WebClient client = new WebClient(); Uri uri = new Uri("http://www.baidu.com"); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressCallback); client.DownloadFileAsync(uri, "serverdata.txt"); }static void client_DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e){// Displays the operation identifier, and the transfer progress.Console.WriteLine("{0}downloaded {1} of {2} bytes. {3} % complete...", (string)e.UserState, e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage); }static void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e){string RetStr = (e.Error == null ? "成功" : e.Error.Message); Console.Write(RetStr); //显示操作结果信息}
三、使用BackgroundWorker组件进行异步编程 BackgroundWorker类就是用EAP实现的。
BackgroundWorker类
公共属性
- CancellationPending:获取一个值,指示应用程序是否已请求取消后台操作
- IsBusy:获取一个值,指示 BackgroundWorker 是否正在运行异步操作。
- WorkReportsProgress:获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。
- WorkerSupportsCancellation:获取或设置一个值,该值指示 BackgroundWorker 是否支持异步取消。
- CancelAsync:请求取消挂起的后台操作。
- ReportProgress:引发 ProgressChanged 事件
- RunWorkerAsync:开始执行后台操作。
- DoWork:调用 RunWorkerAsync 时发生
- ProgressChanged:调用ReportProgress时发生
- RunWorkerCompleted:当后台操作已完成、被取消或引发异常时发生。
文章图片
事件绑定:
文章图片
代码:
public int DownloadSize = 0; public string downloadPath = null; private RequestState requestState = null; private long totalSize = 0; public FileDownloader(){InitializeComponent(); string url = "http://download.microsoft.com/download/7/0/3/703455ee-a747-4cc8-bd3e-98a615c3aedb/dotNetFx35setup.exe"; //string url = "http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe"; txbUrl.Text = url; this.btnPause.Enabled = false; //this.status = DownloadStatus.Initialized; // Get download PathGetTotalSize(); downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + Path.GetFileName(this.txbUrl.Text.Trim()); if (File.Exists(downloadPath)){FileInfo fileInfo = new FileInfo(downloadPath); DownloadSize = (int)fileInfo.Length; progressBar1.Value = https://www.it610.com/article/(int)((float)DownloadSize / (float)totalSize * 100); }// 启用支持 ReportProgress and CancellationbgWorkerFileDownload.WorkerReportsProgress = true; bgWorkerFileDownload.WorkerSupportsCancellation = true; }//开始或恢复下载private void btnDownload_Click(object sender, EventArgs e){if (bgWorkerFileDownload.IsBusy != true){// 启动异步操作触发DoWork事件bgWorkerFileDownload.RunWorkerAsync(); // 创建RequestState 实例requestState = new RequestState(downloadPath); requestState.filestream.Seek(DownloadSize, SeekOrigin.Begin); this.btnDownload.Enabled = false; this.btnPause.Enabled = true; }else{MessageBox.Show("正在执行操作,请稍后"); }}// 暂停下载private void btnPause_Click(object sender, EventArgs e){if (bgWorkerFileDownload.IsBusy && bgWorkerFileDownload.WorkerSupportsCancellation == true){// 终止异步操作触发RunWorkerCompleted事件bgWorkerFileDownload.CancelAsync(); }}#region BackGroundWorker Event// 1、当调用RunWorkerAsync方法时触发private void bgWorkerFileDownload_DoWork(object sender, DoWorkEventArgs e){//获取事件源BackgroundWorker bgworker = sender as BackgroundWorker; try{// 执行下载操作// 初始化一个HttpWebRequest对象HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(txbUrl.Text.Trim()); // 如果文件已下载了一部分,// 服务器应该从DownloadSize开始发送数据到HTTP实体中数据的末尾。if (DownloadSize != 0){myHttpWebRequest.AddRange(DownloadSize); }// 指定一个 HttpWebRequest 实例到request字段.requestState.request = myHttpWebRequest; requestState.response = (HttpWebResponse)myHttpWebRequest.GetResponse(); requestState.streamResponse = requestState.response.GetResponseStream(); int readSize = 0; while (true){if (bgworker.CancellationPending == true){e.Cancel = true; break; }readSize = requestState.streamResponse.Read(requestState.BufferRead, 0, requestState.BufferRead.Length); if (readSize > 0){DownloadSize += readSize; int percentComplete = (int)((float)DownloadSize / (float)totalSize * 100); requestState.filestream.Write(requestState.BufferRead, 0, readSize); // 报告进度,引发ProgressChanged事件的发生bgworker.ReportProgress(percentComplete); }else{break; }}}catch{throw; }}//2、当调用ReportProgress方法时触发private void bgWorkerFileDownload_ProgressChanged(object sender, ProgressChangedEventArgs e){this.progressBar1.Value = https://www.it610.com/article/e.ProgressPercentage; }// 3、当后台操作完成,取消或者有错误时触发private void bgWorkerFileDownload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){if (e.Error != null){MessageBox.Show(e.Error.Message); requestState.response.Close(); }else if (e.Cancelled){MessageBox.Show(String.Format("下载暂停,下载的文件地址为:{0}\n 已经下载的字节数为: {1}字节", downloadPath, DownloadSize)); requestState.response.Close(); requestState.filestream.Close(); this.btnDownload.Enabled = true; this.btnPause.Enabled = false; }else{MessageBox.Show(String.Format("下载已完成,下载的文件地址为:{0},文件的总字节数为: {1}字节", downloadPath, totalSize)); this.btnDownload.Enabled = false; this.btnPause.Enabled = false; requestState.response.Close(); requestState.filestream.Close(); }}#endregion BackGroundWorker Event// 获取文件总大小private void GetTotalSize(){HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(txbUrl.Text.Trim()); HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse(); totalSize = response.ContentLength; response.Close(); }}// 此类存储请求的状态public class RequestState{ public int BufferSize = 2048; public byte[] BufferRead; public HttpWebRequest request; public HttpWebResponse response; public Stream streamResponse; public FileStream filestream; public RequestState(string downloadPath) {BufferRead = new byte[BufferSize]; request = null; streamResponse = null; filestream = new FileStream(downloadPath, FileMode.OpenOrCreate); }
运行程序点击"下载"按钮然后再点击"暂停"后的结果:
文章图片
当暂停下载后,我们还可以点 ”下载“按钮继续下载该文件,此时并不会从开开始下载,而会接着上次的下载继续下载。
这个实现主要是通过AddRange方法来实现的,该方法是指出向服务器请求文件的大小,上面代码中通过传入DownloadSize来告诉服务器,这次我需要的内容不是从开头开始的,而是从已经下载的文件字节数开始到该文件的总的字节结尾,这样就就实现了断点续传的功能了,使户暂停下载不至于之前下载的都白费了。程序的运行结果为:
文章图片
到此这篇关于.NET2.0异步编程模式(EAP)的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
推荐阅读
- .NET1.0版本中的异步编程模型(APM)
- Vue3.2.x中的小技巧及注意事项总结
- C++核心编程中的函数-占位参数和默认参数
- 北亚服务器数据恢复3个磁盘组成的raid5中1个硬盘掉线,阵列出现故障,分区不能识别的数据恢复案例
- spring cloud alibaba springboot nacos 版本对应
- # yyds干货盘点 # 盘点一个Pandas中explode()爆炸函数应用实际案例
- 性能测试中Disruptor框架ExceptionHandler使用分享
- Linux查看版本和系统信息
- Linux如何查看内核版本并安装内核头文件linux-headers-generic
- K8S|在k8s中部署禅道