C#(99):二、.NET 2.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:当后台操作已完成、被取消或引发异常时发生。

下面向大家演示一个使用BackgroundWorker组件实现异步下载文件的一个小程序,该程序支持异步下载(指的就是用线程池线程要执行下载操作),断点续传、下载取消和进度报告的功能。

image

事件绑定:

image

代码:

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 Path

    GetTotalSize();
    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 = (int)((float)DownloadSize / (float)totalSize * 100);
    }

    // 启用支持 ReportProgress and Cancellation
    bgWorkerFileDownload.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 = 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);
 }

运行程序点击"下载"按钮然后再点击"暂停"后的结果:

10001649_dc293a3d48a54471b32aeca5c72d373f[1]

当暂停下载后,我们还可以点 ”下载“按钮继续下载该文件,此时并不会从开开始下载,而会接着上次的下载继续下载。

这个实现主要是通过AddRange方法来实现的,该方法是指出向服务器请求文件的大小,上面代码中通过传入DownloadSize来告诉服务器,这次我需要的内容不是从开头开始的,而是从已经下载的文件字节数开始到该文件的总的字节结尾,这样就就实现了断点续传的功能了,使户暂停下载不至于之前下载的都白费了。程序的运行结果为:

10001620_04976ac9aedf44909ef1c09f4646c5ca[1]

posted on 2020-06-16 11:12  springsnow  阅读(901)  评论(1编辑  收藏  举报

导航