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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM