.NET2.0版本中基于事件的異步編程模式(EAP)
一、引言
APM為我們實現(xiàn)異步編程提供了一定的支持,同時它也存在著一些明顯的問題——不支持對異步操作的取消和沒有提供對進(jìn)度報告的功能,對于有界面的應(yīng)用程序來說,進(jìn)度報告和取消操作的支持也是必不可少的。
微軟在.NET 2.0的時候就為我們提供了一個新的異步編程模型,也就是基于事件的異步編程模型——EAP(Event-based Asynchronous Pattern )。
二、介紹
實現(xiàn)了基于事件的異步模式的類將具有一個或者多個以Async為后綴的方法和對應(yīng)的Completed事件,并且這些類都支持異步方法的取消、進(jìn)度報告和報告結(jié)果。
當(dāng)我們調(diào)用實現(xiàn)基于事件的異步模式的類的 XxxAsync方法時,即代表開始了一個異步操作,該方法調(diào)用完之后會使一個線程池線程去執(zhí)行耗時的操作,所以當(dāng)UI線程調(diào)用該方法時,當(dāng)然也就不會堵塞UI線程了。
并且基于事件的異步模式是建立了APM的基礎(chǔ)之上的,而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); //顯示操作結(jié)果信息
}三、使用BackgroundWorker組件進(jìn)行異步編程
BackgroundWorker類就是用EAP實現(xiàn)的。
BackgroundWorker類
公共屬性
- CancellationPending:獲取一個值,指示應(yīng)用程序是否已請求取消后臺操作
- IsBusy:獲取一個值,指示 BackgroundWorker 是否正在運行異步操作。
- WorkReportsProgress:獲取或設(shè)置一個值,該值指示 BackgroundWorker 能否報告進(jìn)度更新。
- WorkerSupportsCancellation:獲取或設(shè)置一個值,該值指示 BackgroundWorker 是否支持異步取消。
公共方法
- CancelAsync:請求取消掛起的后臺操作。
- ReportProgress:引發(fā) ProgressChanged 事件
- RunWorkerAsync:開始執(zhí)行后臺操作。
公共事件
- DoWork:調(diào)用 RunWorkerAsync 時發(fā)生
- ProgressChanged:調(diào)用ReportProgress時發(fā)生
- RunWorkerCompleted:當(dāng)后臺操作已完成、被取消或引發(fā)異常時發(fā)生。
下面向大家演示一個使用BackgroundWorker組件實現(xiàn)異步下載文件的一個小程序,該程序支持異步下載(指的就是用線程池線程要執(zhí)行下載操作),斷點續(xù)傳、下載取消和進(jìn)度報告的功能。

事件綁定:

代碼:
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;
}
//開始或恢復(fù)下載
private void btnDownload_Click(object sender, EventArgs e)
{
if (bgWorkerFileDownload.IsBusy != true)
{
// 啟動異步操作觸發(fā)DoWork事件
bgWorkerFileDownload.RunWorkerAsync();
// 創(chuàng)建RequestState 實例
requestState = new RequestState(downloadPath);
requestState.filestream.Seek(DownloadSize, SeekOrigin.Begin);
this.btnDownload.Enabled = false;
this.btnPause.Enabled = true;
}
else
{
MessageBox.Show("正在執(zhí)行操作,請稍后");
}
}
// 暫停下載
private void btnPause_Click(object sender, EventArgs e)
{
if (bgWorkerFileDownload.IsBusy && bgWorkerFileDownload.WorkerSupportsCancellation == true)
{
// 終止異步操作觸發(fā)RunWorkerCompleted事件
bgWorkerFileDownload.CancelAsync();
}
}
#region BackGroundWorker Event
// 1、當(dāng)調(diào)用RunWorkerAsync方法時觸發(fā)
private void bgWorkerFileDownload_DoWork(object sender, DoWorkEventArgs e)
{
//獲取事件源
BackgroundWorker bgworker = sender as BackgroundWorker;
try
{
// 執(zhí)行下載操作
// 初始化一個HttpWebRequest對象
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(txbUrl.Text.Trim());
// 如果文件已下載了一部分,
// 服務(wù)器應(yīng)該從DownloadSize開始發(fā)送數(shù)據(jù)到HTTP實體中數(shù)據(jù)的末尾。
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);
// 報告進(jìn)度,引發(fā)ProgressChanged事件的發(fā)生
bgworker.ReportProgress(percentComplete);
}
else
{
break;
}
}
}
catch
{
throw;
}
}
// 2、當(dāng)調(diào)用ReportProgress方法時觸發(fā)
private void bgWorkerFileDownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
// 3、當(dāng)后臺操作完成,取消或者有錯誤時觸發(fā)
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 已經(jīng)下載的字節(jié)數(shù)為: {1}字節(jié)", downloadPath, DownloadSize));
requestState.response.Close();
requestState.filestream.Close();
this.btnDownload.Enabled = true;
this.btnPause.Enabled = false;
}
else
{
MessageBox.Show(String.Format("下載已完成,下載的文件地址為:{0},文件的總字節(jié)數(shù)為: {1}字節(jié)", 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();
}
}
// 此類存儲請求的狀態(tài)
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);
}運行程序點擊"下載"按鈕然后再點擊"暫停"后的結(jié)果:

當(dāng)暫停下載后,我們還可以點 ”下載“按鈕繼續(xù)下載該文件,此時并不會從開開始下載,而會接著上次的下載繼續(xù)下載。
這個實現(xiàn)主要是通過AddRange方法來實現(xiàn)的,該方法是指出向服務(wù)器請求文件的大小,上面代碼中通過傳入DownloadSize來告訴服務(wù)器,這次我需要的內(nèi)容不是從開頭開始的,而是從已經(jīng)下載的文件字節(jié)數(shù)開始到該文件的總的字節(jié)結(jié)尾,這樣就就實現(xiàn)了斷點續(xù)傳的功能了,使戶暫停下載不至于之前下載的都白費了。程序的運行結(jié)果為:

到此這篇關(guān)于.NET2.0異步編程模式(EAP)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
一步步打造漂亮的新聞列表(無刷新分頁、內(nèi)容預(yù)覽)第三章
前面兩個章節(jié)我們將需求分析和概要設(shè)計簡單介紹了,接下來是重點的編代碼的階段了(實現(xiàn)無刷新分頁)。在編寫代碼之前,一定要有計劃的去編寫代碼,不能一開始啥也不管就開始編代碼,除非你特牛。2010-07-07
詳解Asp.net 5中的ApplicationBuilder
這篇文章介紹了Asp.net 5中的ApplicationBuilder,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01
AjaxControlToolKit DropDownExtender(下拉擴展控件)使用方法
由于工作的需要,使用了這個控件 挺簡單,使用這個擴展控件能輕松的吧 Label 控件 TextBox控件擴展成類似DropDownList控件的功能。這樣使用既可以使用label控件或者textBox控件的一些屬性又能實現(xiàn)dropDownList的功能。2008-10-10
ASP.NET?Core中的Configuration配置一
這篇文章介紹了ASP.NET?Core中的Configuration配置,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
.NET?6全新配置對象ConfigurationManager介紹
這篇文章介紹了.NET?6全新配置對象ConfigurationManager,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-11-11
通過VS中的數(shù)據(jù)源選擇對話框簡單實現(xiàn)數(shù)據(jù)庫連接配置
通過VS中的數(shù)據(jù)源選擇對話框簡單實現(xiàn)數(shù)據(jù)庫連接配置...2007-02-02

