APM模式:
.net 1.0时期就提出的一种异步模式,并且基于IAsyncResult接口实现BeginXXX和EndXXX类似的方法。
.net中有很多类实现了该模式(比如HttpWebRequest),同时我们也可以自定义类来实现APM模式(继承IAsyncResult接口并且实现BeginXXX和EndXXX方法)
1 /// <summary>2 /// 异步3 /// </summary>4 /// <param name="sender"></param>5 /// <param name="e"></param>6 private void button2_Click(object sender, EventArgs e)7 {8 //先清空上一次查询结果9 this.richTextBox1.Text = "";
10
11 var url = this.textBox1.Text.Trim();
12 var request = HttpWebRequest.Create(url);
13 request.BeginGetResponse(AsyncCallbackImpl, request);//BeginGetResponse,发起异步请求
14 }
15
16 /// <summary>
17 /// 回调
18 /// </summary>
19 /// <param name="ar"></param>
20 public void AsyncCallbackImpl(IAsyncResult ar)
21 {
22 HttpWebRequest request = ar.AsyncState as HttpWebRequest;
23 var response = request.EndGetResponse(ar);//EndGetResponse,异步请求完成
24 var stream = response.GetResponseStream();
25 StringBuilder sb = new StringBuilder();
26 sb.AppendLine("当前线程Id:" + Thread.CurrentThread.ManagedThreadId);
27 using (StreamReader reader = new StreamReader(stream))
28 {
29 var content = reader.ReadLine();
30 sb.AppendLine(content);
31 this.richTextBox1.Text = sb.ToString();
32 }
33 }
34
1 Func<int, int> func = (i) => i + 1;
2 func.BeginInvoke(5, (asyncResult) => {
3 //Console.WriteLine("call back,param:"+result.AsyncState);
4 int result = func.EndInvoke(asyncResult);
5 Console.WriteLine("result:"+ result);
6 }, null);
EAP模式:
基于事件的异步模式是.net 2.0提出的,实现了基于事件的异步模式的类将具有一个或者多个以Async为后缀的方法和对应的Completed事件,并且这些类都支持异步方法的取消、进度报告和报告结果。然而.net中并不是所有的类都支持EAP。
当调用基于事件的EAP模式的类的XXXAsync方法时,就开始了一个异步操作,并且基于事件的EAP模式是基于APM模式之上的,而APM又是建立在委托之上的。下面的Demo就以BackgroundWorker类来演示如何使用EAP异步。
1 BackgroundWorker worker = new BackgroundWorker();2 worker.DoWork += Worker_DoWork;3 worker.RunWorkerCompleted += Worker_RunWorkerCompleted;4 worker.RunWorkerAsync(null);5 6 private static void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)7 {8 Console.WriteLine("dowork completed");9 }
10
11 private static void Worker_DoWork(object sender, DoWorkEventArgs e)
12 {
13 Console.WriteLine("dowork");
14 }
TAP模式:
.net 4.0为我们带来了Task的异步,我们有以下三种方法创建Task。
1,Task.Factory.StartNew,比较常用。
2,Task t1 = new Task(() => { Console.WriteLine("t1 start"); }); t1.Start();
3,Task.Run,是.net 4.5中增加的。
4,Task.FromResult,如果结果是已计算,就可以使用这种方法来创建任务。
1 /// <summary>2 /// 使用async/await3 /// </summary>4 /// <param name="sender"></param>5 /// <param name="e"></param>6 private async void button5_Click(object sender, EventArgs e)7 {8 this.richTextBox1.Text = "正在处理请求...";9
10 await DoWorkAsync();
11 }
12
13 public async Task DoWorkAsync()
14 {
15 var url = this.textBox1.Text.Trim();
16 var request = HttpWebRequest.Create(url);
17 var response = request.GetResponse();
18 var stream = response.GetResponseStream();
19 using (StreamReader reader = new StreamReader(stream))
20 {
21 var content = reader.ReadToEnd();
22 this.richTextBox1.Text = content;
23 }
24 }
25
26 View Code