APM模式:
.net 1.0时期就提出的一种异步模式,并且基于IAsyncResult接口实现BeginXXX和EndXXX类似的方法。
.net中有很多类实现了该模式(比如HttpWebRequest),同时我们也可以自定义类来实现APM模式(继承IAsyncResult接口并且实现BeginXXX和EndXXX方法)
/// <summary>
/// 异步
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//先清空上一次查询结果
this.richTextBox1.Text = ""; var url = this.textBox1.Text.Trim();
var request = HttpWebRequest.Create(url);
request.BeginGetResponse(AsyncCallbackImpl, request);//BeginGetResponse,发起异步请求
} /// <summary>
/// 回调
/// </summary>
/// <param name="ar"></param>
public void AsyncCallbackImpl(IAsyncResult ar)
{
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
var response = request.EndGetResponse(ar);//EndGetResponse,异步请求完成
var stream = response.GetResponseStream();
StringBuilder sb = new StringBuilder();
sb.AppendLine("当前线程Id:" + Thread.CurrentThread.ManagedThreadId);
using (StreamReader reader = new StreamReader(stream))
{
var content = reader.ReadLine();
sb.AppendLine(content);
this.richTextBox1.Text = sb.ToString();
}
}
Func<int, int> func = (i) => i + ;
func.BeginInvoke(, (asyncResult) => {
//Console.WriteLine("call back,param:"+result.AsyncState);
int result = func.EndInvoke(asyncResult);
Console.WriteLine("result:"+ result);
}, null);
EAP模式:
基于事件的异步模式是.net 2.0提出的,实现了基于事件的异步模式的类将具有一个或者多个以Async为后缀的方法和对应的Completed事件,并且这些类都支持异步方法的取消、进度报告和报告结果。然而.net中并不是所有的类都支持EAP。
当调用基于事件的EAP模式的类的XXXAsync方法时,就开始了一个异步操作,并且基于事件的EAP模式是基于APM模式之上的,而APM又是建立在委托之上的。下面的Demo就以BackgroundWorker类来演示如何使用EAP异步。
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += Worker_DoWork;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
worker.RunWorkerAsync(null); private static void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("dowork completed");
} private static void Worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("dowork");
}
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(),如果结果是已计算,就可以使用这种方法来创建任务。
/// <summary>
/// 使用async/await
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void button5_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "正在处理请求..."; await DoWorkAsync();
} public async Task DoWorkAsync()
{
var url = this.textBox1.Text.Trim();
var request = HttpWebRequest.Create(url);
var response = request.GetResponse();
var stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
this.richTextBox1.Text = content;
}
}