开卷目录
新进阶的程序员可能对async、await用得相比较多,却对前边的异步了解什么少。本人就是此类,由此打算回顾学习下异步的进化史。
本文紧要是回顾async异步模式此前的异步,下篇著作再来重点解析async异步格局。
新进阶的程序员可能对async、await用得相比多,却对从前的异步领会什么少。本人就是此类,由此打算回顾学习下异步的进化史。
APM
APM 异步编程模型,Asynchronous Programming Model
早在C#1的时候就有了APM。即便不是很谙习,可是有些仍然见过的。就是那一个类是BeginXXX和EndXXX的不二法门,且BeginXXX重回值是IAsyncResult接口。
在专业写APM示例在此之前我们先交由一段同步代码:
//1、同步方法
private void button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】线程ID:" + Thread.CurrentThread.ManagedThreadId);
var request = WebRequest.Create("https://github.com/");//为了更好的演示效果,我们使用网速比较慢的外网
request.GetResponse();//发送请求
Debug.WriteLine("【Debug】线程ID:" + Thread.CurrentThread.ManagedThreadId);
label1.Text = "执行完毕!";
}
【表达】为了更好的演示异步效果,这里大家使用winform程序来做示范。(因为winform始终都亟需UI线程渲染界面,假设被UI线程占用则会见世“假死”状态)
【效果图】
看图得知:
- 我们在实践办法的时候页面出现了“假死”,拖不动了。
- 我们看到打印结果,方法调用前和调用后线程ID都是9(也就是同一个线程)
上面我们再来演示对应的异步方法:(BeginGetResponse、EndGetResponse所谓的APM异步模型)
private void button2_Click(object sender, EventArgs e)
{
//1、APM 异步编程模型,Asynchronous Programming Model
//C#1[基于IAsyncResult接口实现BeginXXX和EndXXX的方法]
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
var request = WebRequest.Create("https://github.com/");
request.BeginGetResponse(new AsyncCallback(t =>//执行完成后的回调
{
var response = request.EndGetResponse(t);
var stream = response.GetResponseStream();//获取返回数据流
using (StreamReader reader = new StreamReader(stream))
{
StringBuilder sb = new StringBuilder();
while (!reader.EndOfStream)
{
var content = reader.ReadLine();
sb.Append(content);
}
Debug.WriteLine("【Debug】" + sb.ToString().Trim().Substring(0, 100) + "...");//只取返回内容的前100个字符
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
label1.Invoke((Action)(() => { label1.Text = "执行完毕!"; }));//这里跨线程访问UI需要做处理
}
}), null);
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
【效果图】
看图得知:
- 启用异步方法并从未是UI界面卡死
- 异步方法启动了其余一个ID为12的线程
地点代码执行顺序:
面前大家说过,APM的BebinXXX必须重返IAsyncResult接口。那么接下去大家解析IAsyncResult接口:
先是大家看:
诚然重返的是IAsyncResult接口。那IAsyncResult到底长的什么体统?:
并从未想像中的那么复杂嘛。大家是否足以尝尝这贯彻这么些接口,然后展现自己的异步方法吗?
先是定一个类MyWebRequest,然后继续IAsyncResult:(上面是焦点的伪代码实现)
public class MyWebRequest : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException(); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException(); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException(); }
}
public bool IsCompleted
{
get { throw new NotImplementedException(); }
}
}
如此这般自然是不可能用的,起码也得有个存回调函数的性质吧,下边我们有点改造下:
接下来我们得以自定义APM异步模型了:(成对的Begin、End)
public IAsyncResult MyBeginXX(AsyncCallback callback)
{
var asyncResult = new MyWebRequest(callback, null);
var request = WebRequest.Create("https://github.com/");
new Thread(() => //重新启用一个线程
{
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
var str = sr.ReadToEnd();
asyncResult.SetComplete(str);//设置异步结果
}
}).Start();
return asyncResult;//返回一个IAsyncResult
}
public string MyEndXX(IAsyncResult asyncResult)
{
MyWebRequest result = asyncResult as MyWebRequest;
return result.Result;
}
调用如下:
private void button4_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
MyBeginXX(new AsyncCallback(t =>
{
var result = MyEndXX(t);
Debug.WriteLine("【Debug】" + result.Trim().Substring(0, 100) + "...");
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
}));
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
效果图:
咱俩看看自己实现的效劳基本上和序列提供的大半。
- 启用异步方法并没有是UI界面卡死
- 异步方法启动了此外一个ID为11的线程
【总结】
村办觉得APM异步形式就是启用其余一个线程执行耗时任务,然后经过回调函数执行后续操作。
APM仍可以够透过任何艺术赢得值,如:
while (!asyncResult.IsCompleted)//循环,直到异步执行完成 (轮询方式)
{
Thread.Sleep(100);
}
var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();
或
asyncResult.AsyncWaitHandle.WaitOne();//阻止线程,直到异步完成 (阻塞等待)
var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();
填补:假使是惯常方法,大家也得以通过委托异步:(BeginInvoke、EndInvoke)
public void MyAction()
{
var func = new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "name:" + t + DateTime.Now.ToString();
});
var asyncResult = func.BeginInvoke("张三", t =>
{
string str = func.EndInvoke(t);
Debug.WriteLine(str);
}, null);
}
正文紧假诺回顾async异步格局在此以前的异步,下篇作品再来重点解析async异步情势。
EAP
EAP 基于事件的异步情势,伊夫nt-based Asynchronous Pattern
此形式在C#2的时候光顾。
先来看个EAP的事例:
private void button3_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((s1, s2) =>
{
Thread.Sleep(2000);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
});//注册事件来实现异步
worker.RunWorkerAsync(this);
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
【效果图】(同样不会阻塞UI界面)
【特征】
- 经过事件的法门注册回调函数
- 由此 XXXAsync方法来施行异步调用
事例很简短,可是和APM情势相比,是不是从未有过那么清晰透明。为啥可以这样实现?事件的注册是在干嘛?为啥执行RunWorkerAsync会触发注册的函数?
感到温馨又想多了…
咱俩试着反编译看看源码:
只想说,这么玩,有意思吗?
APM
APM 异步编程模型,Asynchronous Programming Model
早在C#1的时候就有了APM。即使不是很熟谙,不过有些仍然见过的。就是这几个类是BeginXXX和EndXXX的不二法门,且BeginXXX重临值是IAsyncResult接口。
在专业写APM示例在此以前大家先交付一段同台代码:
//1、同步方法
private void button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】线程ID:" + Thread.CurrentThread.ManagedThreadId);
var request = WebRequest.Create("https://github.com/");//为了更好的演示效果,我们使用网速比较慢的外网
request.GetResponse();//发送请求
Debug.WriteLine("【Debug】线程ID:" + Thread.CurrentThread.ManagedThreadId);
label1.Text = "执行完毕!";
}
【表达】为了更好的言传身教异步效果,这里咱们接纳winform程序来做示范。(因为winform始终都亟需UI线程渲染界面,假若被UI线程占用则会现出“假死”状态)
【效果图】
看图得知:
- 我们在实施措施的时候页面出现了“假死”,拖不动了。
- 我们来看打印结果,方法调用前和调用后线程ID都是9(也就是同一个线程)
上面咱们再来演示对应的异步方法:(BeginGetResponse、EndGetResponse所谓的APM异步模型)
private void button2_Click(object sender, EventArgs e)
{
//1、APM 异步编程模型,Asynchronous Programming Model
//C#1[基于IAsyncResult接口实现BeginXXX和EndXXX的方法]
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
var request = WebRequest.Create("https://github.com/");
request.BeginGetResponse(new AsyncCallback(t =>//执行完成后的回调
{
var response = request.EndGetResponse(t);
var stream = response.GetResponseStream();//获取返回数据流
using (StreamReader reader = new StreamReader(stream))
{
StringBuilder sb = new StringBuilder();
while (!reader.EndOfStream)
{
var content = reader.ReadLine();
sb.Append(content);
}
Debug.WriteLine("【Debug】" + sb.ToString().Trim().Substring(0, 100) + "...");//只取返回内容的前100个字符
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
label1.Invoke((Action)(() => { label1.Text = "执行完毕!"; }));//这里跨线程访问UI需要做处理
}
}), null);
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
【效果图】
看图得知:
- 启用异步方法并从未是UI界面卡死
- 异步方法启动了此外一个ID为12的线程
地点代码执行顺序:
前方我们说过,APM的BebinXXX必须重临IAsyncResult接口。那么接下去大家解析IAsyncResult接口:
首先我们看:
确实重回的是IAsyncResult接口。这IAsyncResult到底长的什么样体统?:
并不曾想像中的那么复杂嘛。大家是否足以尝尝那贯彻这一个接口,然后显示自己的异步方法吧?
先是定一个类MyWebRequest,然后继续IAsyncResult:(下边是骨干的伪代码实现)
public class MyWebRequest : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException(); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException(); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException(); }
}
public bool IsCompleted
{
get { throw new NotImplementedException(); }
}
}
这般自然是不可以用的,起码也得有个存回调函数的性能吧,下边我们稍事改造下:
下一场我们能够自定义APM异步模型了:(成对的Begin、End)
public IAsyncResult MyBeginXX(AsyncCallback callback)
{
var asyncResult = new MyWebRequest(callback, null);
var request = WebRequest.Create("https://github.com/");
new Thread(() => //重新启用一个线程
{
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
var str = sr.ReadToEnd();
asyncResult.SetComplete(str);//设置异步结果
}
}).Start();
return asyncResult;//返回一个IAsyncResult
}
public string MyEndXX(IAsyncResult asyncResult)
{
MyWebRequest result = asyncResult as MyWebRequest;
return result.Result;
}
调用如下:
private void button4_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
MyBeginXX(new AsyncCallback(t =>
{
var result = MyEndXX(t);
Debug.WriteLine("【Debug】" + result.Trim().Substring(0, 100) + "...");
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
}));
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
效果图:
咱俩来看自己实现的效劳基本上和系统提供的基本上。
- 启用异步方法并从未是UI界面卡死
- 异步方法启动了此外一个ID为11的线程
【总结】
民用觉得APM异步情势就是启用另外一个线程执行耗时任务,然后经过回调函数执行后续操作。
APM还足以通过其他艺术赢得值,如:
while (!asyncResult.IsCompleted)//循环,直到异步执行完成 (轮询方式)
{
Thread.Sleep(100);
}
var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();
或
asyncResult.AsyncWaitHandle.WaitOne();//阻止线程,直到异步完成 (阻塞等待)
var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();
增补:假使是普普通通方法,大家也足以由此委托异步:(BeginInvoke、EndInvoke)
public void MyAction()
{
var func = new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "name:" + t + DateTime.Now.ToString();
});
var asyncResult = func.BeginInvoke("张三", t =>
{
string str = func.EndInvoke(t);
Debug.WriteLine(str);
}, null);
}
TAP
TAP 基于任务的异步情势,Task-based Asynchronous Pattern
到近来截止,我们认为上边的APM、EAP异步形式好用啊?好像平昔不意识什么问题。再精心想想…假如大家有三个异步方法需要按先后顺序执行,并且需要(在主进程)得到所有再次回到值。
首先定义两个委托:
public Func<string, string> func1()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "name:" + t;
});
}
public Func<string, string> func2()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "age:" + t;
});
}
public Func<string, string> func3()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "sex:" + t;
});
}
然后遵照一定顺序执行:
public void MyAction()
{
string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;
IAsyncResult asyncResult1 = null, asyncResult2 = null, asyncResult3 = null;
asyncResult1 = func1().BeginInvoke("张三", t =>
{
str1 = func1().EndInvoke(t);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
asyncResult2 = func2().BeginInvoke("26", a =>
{
str2 = func2().EndInvoke(a);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
asyncResult3 = func3().BeginInvoke("男", s =>
{
str3 = func3().EndInvoke(s);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
}, null);
}, null);
}, null);
asyncResult1.AsyncWaitHandle.WaitOne();
asyncResult2.AsyncWaitHandle.WaitOne();
asyncResult3.AsyncWaitHandle.WaitOne();
Debug.WriteLine(str1 + str2 + str3);
}
除却难看、难读一点近似也没怎么 。可是真正是如此吧?
asyncResult2是null?
有鉴于此在做到第一个异步操作从前从没对asyncResult2举办赋值,asyncResult2执行异步等待的时候报这多少个。那么这样我们就无法控制五个异步函数,遵照一定顺序执行到位后再得到再次回到值。(理论上或者有任何情势的,只是会然代码更加错综复杂)
正确,现在该我们的TAP登场了。
只需要调用Task类的静态方法Run,即可轻松使用异步。
获取重回值:
var task1 = Task<string>.Run(() =>
{
Thread.Sleep(1500);
Console.WriteLine("【Debug】task1 线程ID:" + Thread.CurrentThread.ManagedThreadId);
return "张三";
});
//其他逻辑
task1.Wait();
var value = task1.Result;//获取返回值
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
后天我们处理方面六个异步按序执行:
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;
var task1 = Task.Run(() =>
{
Thread.Sleep(500);
str1 = "姓名:张三,";
Console.WriteLine("【Debug】task1 线程ID:" + Thread.CurrentThread.ManagedThreadId);
}).ContinueWith(t =>
{
Thread.Sleep(500);
str2 = "年龄:25,";
Console.WriteLine("【Debug】task2 线程ID:" + Thread.CurrentThread.ManagedThreadId);
}).ContinueWith(t =>
{
Thread.Sleep(500);
str3 = "爱好:妹子";
Console.WriteLine("【Debug】task3 线程ID:" + Thread.CurrentThread.ManagedThreadId);
});
Thread.Sleep(2500);//其他逻辑代码
task1.Wait();
Debug.WriteLine(str1 + str2 + str3);
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
[效果图]
大家看看,结果都拿走了,且是异步按序执行的。且代码的逻辑思路特别明显。倘若您感触还不是很大,那么你现象一经是100个异步方法需要异步按序执好吗?用APM的异步回调,这至少也得异步回调嵌套100次。这代码的复杂度由此可见。
EAP
EAP 基于事件的异步形式,伊夫(Eve)nt-based Asynchronous Pattern
此形式在C#2的时候光顾。
先来看个EAP的事例:
private void button3_Click(object sender, EventArgs e)
{
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((s1, s2) =>
{
Thread.Sleep(2000);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
});//注册事件来实现异步
worker.RunWorkerAsync(this);
Debug.WriteLine("【Debug】主线程ID:" + Thread.CurrentThread.ManagedThreadId);
}
【效果图】(同样不会阻塞UI界面)
【特征】
- 透过事件的法门注册回调函数
- 由此 XXXAsync方法来执行异步调用
事例很简单,可是和APM情势相比,是不是没有那么清楚透明。为啥可以如此实现?事件的登记是在干嘛?为何执行RunWorkerAsync会触发注册的函数?
深感温馨又想多了…
俺们试着反编译看看源码:
只想说,这么玩,有意思啊?
拉开思考
-
WaitOne完成等待的法则
-
异步为何会升级性能
-
线程的选用数据和CPU的使用率有肯定的联系呢
题目1:WaitOne完成等待的法则
从前,咱们先来简单的问询下多线程信号控制AutoReset伊芙nt类。
var _asyncWaitHandle = new AutoResetEvent(false);
_asyncWaitHandle.WaitOne();
此代码会在 WaitOne 的地方会直接等候下去。除非有其它一个线程执行 AutoReset伊夫nt 的set方法。
var _asyncWaitHandle = new AutoResetEvent(false);
_asyncWaitHandle.Set();
_asyncWaitHandle.WaitOne();
这么,到了 WaitOne 就足以直接执行下去。没有有另外等待。
当今咱们对APM 异步编程模型中的 WaitOne 等待是不是领略了点什么呢。我们回头来实现以前自定义异步方法的异步等待。
public class MyWebRequest : IAsyncResult
{
//异步回调函数(委托)
private AsyncCallback _asyncCallback;
private AutoResetEvent _asyncWaitHandle;
public MyWebRequest(AsyncCallback asyncCallback, object state)
{
_asyncCallback = asyncCallback;
_asyncWaitHandle = new AutoResetEvent(false);
}
//设置结果
public void SetComplete(string result)
{
Result = result;
IsCompleted = true;
_asyncWaitHandle.Set();
if (_asyncCallback != null)
{
_asyncCallback(this);
}
}
//异步请求返回值
public string Result { get; set; }
//获取用户定义的对象,它限定或包含关于异步操作的信息。
public object AsyncState
{
get { throw new NotImplementedException(); }
}
// 获取用于等待异步操作完成的 System.Threading.WaitHandle。
public WaitHandle AsyncWaitHandle
{
//get { throw new NotImplementedException(); }
get { return _asyncWaitHandle; }
}
//获取一个值,该值指示异步操作是否同步完成。
public bool CompletedSynchronously
{
get { throw new NotImplementedException(); }
}
//获取一个值,该值指示异步操作是否已完成。
public bool IsCompleted
{
get;
private set;
}
}
绿色代码就是增创的异步等待。
【执行步骤】
问题2:异步为啥会进步性能
比如说同步代码:
Thread.Sleep(10000);//假设这是个访问数据库的方法
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
本条代码需要20秒。
倘诺是异步:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
task.Wait();
如此就假使10秒了。这样就节省了10秒。
如果是:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
task.Wait();
异步执行中间没有耗时的代码那么那样的异步将是不曾意思的。
或者:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
task.Wait();
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
把耗时任务放在异步等待后,这这样的代码也是不会有性能提高的。
再有一种情景:
假定是单核CPU进行高密集运算操作,那么异步也是尚未意思的。(因为运算是这一个耗CPU,而网络请求等待不耗CPU)
问题3:线程的使用数据和CPU的使用率有自然的联系呢
答案是否。
要么拿单核做假如。
情况1:
long num = 0;
while (true)
{
num += new Random().Next(-100,100);
//Thread.Sleep(100);
}
单核下,我们只启动一个线程,就足以让你CPU爆满。
起始八次,八历程CPU基本满员。
情况2:
一千两个线程,而CPU的使用率竟然是0。因此,我们得到了往日的定论,线程的施用数据和CPU的使用率没有早晚的交换。
尽管这么,可是也无法不要节制的开启线程。因为:
- 拉开一个新的线程的历程是相比较耗资源的。(不过使用线程池,来下滑开启新线程所消耗的资源)
- 多线程的切换也是索要时日的。
- 每个线程占用了一定的内存保存线程上下文信息。
demo:http://pan.baidu.com/s/1slOxgnF
TAP
TAP 基于任务的异步形式,Task-based Asynchronous Pattern
到目前截止,我们以为下面的APM、EAP异步格局好用呢?好像从没发现什么样问题。再精心想想…倘使我们有三个异步方法需要按先后顺序执行,并且需要(在主进程)得到所有再次来到值。
第一定义五个委托:
public Func<string, string> func1()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "name:" + t;
});
}
public Func<string, string> func2()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "age:" + t;
});
}
public Func<string, string> func3()
{
return new Func<string, string>(t =>
{
Thread.Sleep(2000);
return "sex:" + t;
});
}
然后按照一定顺序执行:
public void MyAction()
{
string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;
IAsyncResult asyncResult1 = null, asyncResult2 = null, asyncResult3 = null;
asyncResult1 = func1().BeginInvoke("张三", t =>
{
str1 = func1().EndInvoke(t);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
asyncResult2 = func2().BeginInvoke("26", a =>
{
str2 = func2().EndInvoke(a);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
asyncResult3 = func3().BeginInvoke("男", s =>
{
str3 = func3().EndInvoke(s);
Debug.WriteLine("【Debug】异步线程ID:" + Thread.CurrentThread.ManagedThreadId);
}, null);
}, null);
}, null);
asyncResult1.AsyncWaitHandle.WaitOne();
asyncResult2.AsyncWaitHandle.WaitOne();
asyncResult3.AsyncWaitHandle.WaitOne();
Debug.WriteLine(str1 + str2 + str3);
}
除开难看、难读一点接近也没怎么 。然而真的是这般啊?
asyncResult2是null?
有鉴于此在形成第一个异步操作此前并未对asyncResult2举行赋值,asyncResult2执行异步等待的时候报这个。那么如此大家就不可以控制四个异步函数,遵照一定顺序执行到位后再得到重返值。(理论上如故有任何措施的,只是会然代码更加扑朔迷离)
是的,现在该我们的TAP登场了。
只需要调用Task类的静态方法Run,即可轻松使用异步。
拿到重返值:
var task1 = Task<string>.Run(() =>
{
Thread.Sleep(1500);
Console.WriteLine("【Debug】task1 线程ID:" + Thread.CurrentThread.ManagedThreadId);
return "张三";
});
//其他逻辑
task1.Wait();
var value = task1.Result;//获取返回值
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
现在大家处理地点六个异步按序执行:
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;
var task1 = Task.Run(() =>
{
Thread.Sleep(500);
str1 = "姓名:张三,";
Console.WriteLine("【Debug】task1 线程ID:" + Thread.CurrentThread.ManagedThreadId);
}).ContinueWith(t =>
{
Thread.Sleep(500);
str2 = "年龄:25,";
Console.WriteLine("【Debug】task2 线程ID:" + Thread.CurrentThread.ManagedThreadId);
}).ContinueWith(t =>
{
Thread.Sleep(500);
str3 = "爱好:妹子";
Console.WriteLine("【Debug】task3 线程ID:" + Thread.CurrentThread.ManagedThreadId);
});
Thread.Sleep(2500);//其他逻辑代码
task1.Wait();
Debug.WriteLine(str1 + str2 + str3);
Console.WriteLine("【Debug】主 线程ID:" + Thread.CurrentThread.ManagedThreadId);
[效果图]
咱俩来看,结果都拿到了,且是异步按序执行的。且代码的逻辑思路异常明晰。假若您感触还不是很大,那么你现象一经是100个异步方法需要异步按序执好吗?用APM的异步回调,这至少也得异步回调嵌套100次。这代码的复杂度显而易见。
拉开思考
-
WaitOne完成等待的法则
-
异步为啥会升级性能
-
线程的接纳数据和CPU的使用率有自然的关联吗
问题1:WaitOne完成等待的法则
在此以前,我们先来大概的问询下多线程信号控制AutoReset伊夫(Eve)nt类。
var _asyncWaitHandle = new AutoResetEvent(false);
_asyncWaitHandle.WaitOne();
此代码会在 WaitOne 的地点会间接等候下去。除非有此外一个线程执行 AutoReset伊夫(Eve)nt 的set方法。
var _asyncWaitHandle = new AutoResetEvent(false);
_asyncWaitHandle.Set();
_asyncWaitHandle.WaitOne();
这般,到了 WaitOne 就足以直接执行下去。没有有此外等待。
现今我们对APM 异步编程模型中的 WaitOne 等待是不是领略了点什么吧。我们回头来贯彻以前自定义异步方法的异步等待。
public class MyWebRequest : IAsyncResult
{
//异步回调函数(委托)
private AsyncCallback _asyncCallback;
private AutoResetEvent _asyncWaitHandle;
public MyWebRequest(AsyncCallback asyncCallback, object state)
{
_asyncCallback = asyncCallback;
_asyncWaitHandle = new AutoResetEvent(false);
}
//设置结果
public void SetComplete(string result)
{
Result = result;
IsCompleted = true;
_asyncWaitHandle.Set();
if (_asyncCallback != null)
{
_asyncCallback(this);
}
}
//异步请求返回值
public string Result { get; set; }
//获取用户定义的对象,它限定或包含关于异步操作的信息。
public object AsyncState
{
get { throw new NotImplementedException(); }
}
// 获取用于等待异步操作完成的 System.Threading.WaitHandle。
public WaitHandle AsyncWaitHandle
{
//get { throw new NotImplementedException(); }
get { return _asyncWaitHandle; }
}
//获取一个值,该值指示异步操作是否同步完成。
public bool CompletedSynchronously
{
get { throw new NotImplementedException(); }
}
//获取一个值,该值指示异步操作是否已完成。
public bool IsCompleted
{
get;
private set;
}
}
红色代码就是骤增的异步等待。
【执行步骤】
问题2:异步为啥会提高性能
譬如说同步代码:
Thread.Sleep(10000);//假设这是个访问数据库的方法
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
以此代码需要20秒。
固然是异步:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
task.Wait();
如此这般就假使10秒了。这样就节省了10秒。
如果是:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
task.Wait();
异步执行中间没有耗时的代码那么那样的异步将是从未有过意思的。
或者:
var task = Task.Run(() =>
{
Thread.Sleep(10000);//假设这是个访问数据库的方法
});
task.Wait();
Thread.Sleep(10000);//假设这是个访问FQ网站的方法
把耗时任务放在异步等待后,这这样的代码也是不会有性能进步的。
再有一种状况:
只如若单核CPU举办高密集运算操作,那么异步也是从未有过意思的。(因为运算是可怜耗CPU,而网络请求等待不耗CPU)
问题3:线程的选择数据和CPU的使用率有肯定的联络吗
答案是否。
仍然拿单核做尽管。
情况1:
long num = 0;
while (true)
{
num += new Random().Next(-100,100);
//Thread.Sleep(100);
}
单核下,大家只启动一个线程,就足以让您CPU爆满。
启动八次,八历程CPU基本满员。
情况2:
一千五个线程,而CPU的使用率竟然是0。因而,大家获取了前边的下结论,线程的采纳数据和CPU的使用率没有必然的维系。
尽管如此,可是也不可以不要节制的开启线程。因为:
- 开启一个新的线程的长河是相比较耗资源的。(不过使用线程池,来下滑开启新线程所消耗的资源)
- 多线程的切换也是急需时间的。
- 各类线程占用了必然的内存保存线程上下文音信。
demo:http://pan.baidu.com/s/1slOxgnF
本文已协同至索引目录:《C#基础知识巩固》
对此异步编程了然不深,文中极有可能多处错误描述和见解。
感谢广大园友的指正。
本着互相探究的目的,绝无想要误导我们的趣味。
【推荐】
http://www.cnblogs.com/wisdomqq/archive/2012/03/26/2412349.html