C#~异步编程再续~async异步方法与同步方法的并行

返回目录

今天晚上没事写了个测试的代码,又看了看.net的并行编程,两个方法,一个是异步async修饰的,另一个是普通的方法,在控制台程序的Main方法里去调用这两个方法,会有什么结果呢?

首先我们看一下方法的组成,step1如下

 public async void Step1()
{
try
{
//await进行等待后,新线程的异常可以被主线程捕捉,这是正常的,下面的代码不会被执行
await Task.Run(() =>
{ Console.WriteLine("Step1 Current ThreadID" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}); await Task.Run(() =>
{
Console.WriteLine("Step1 Current ThreadID" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("ThreadTest.Test Runing");
});
}
catch (Exception ex)
{ Console.WriteLine("ThreadTest" + ex.Message);
}
}

step2如下

 public void Step2()
{
Console.WriteLine("Step2 Current ThreadID" + Thread.CurrentThread.ManagedThreadId);
}

我们可以看到step2很简单,不会有什么延时,就是在屏幕上输出一段话,而step1就显得复杂一些了,它是一个异步的方法,并且使用Task.Run开启了两个新线程,而第一

个线程的运行时间是3秒,很长呀,哈哈,第二个是在屏幕上输出一段话!现在我们把step1和step2写在一起会出现什么情况呢?

 var test = new ThreadTest();
test.Step1();//整个方法不阻塞,但方法内部有可能阻塞
test.Step2();

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAAB2CAIAAAC/PkqQAAAMq0lEQVR4nO2dW48UxxXH++PMS/geUZSb2iKsYytSnpIoisRLpEYJkRNZxibYsbGFIek4i+PYRlwEKAYbGGYX+wFjywzscluWYXZZBsJe2IUsu7EQeeiZnuqqc05X9XT37s78f9qH7uqqc06fqn9V9cw0ePfv379z587k5OQLz295BgBQ8O7duzc9PX3z5k3IAwANr9VqNZvNGzduQB4AaHh37969ffv29evXIQ8ANLyZmZlGo3Ht2rVUedQvjdVGztn8Xaxffvr0aTk3AEBxeHfu3Ll169bVq1dT5XHoyPGvLo5/dXHM+Bv/uj7+dX382Kejx06OHDs58q8Dh2dnZ8u5AQCKw5uenp6cnLxy5Uq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yxL8m8iDj9BRhQB75U/7bgnJDSzs5ysPJr9yKIxd5pFqGPPKn5LcFOcscNt1vzqapprhCG/kJ1ThylwfZEZb5SY3Hsr9ck7AhKfltQRsXXH2hvEZh6dG8JJ9yebCPn7PvGqcWieBFO5ADEPxmTsJGBW8LAsCCtwUBYMEvdgFggTwAYIE8AGCBPABggTwAYFHlYfPpe5msVTzrx2/v1vKJbGDR5BEVagclJzp2x8VTQgBr4td01ItfyCMHuB+0a9VKTnSOo6QXO+X7LejGQUYgjxzr924H8lhfOMlD2xOrp+Z2mdtDcxvrWhLTu1A/1Y5gXKB8v4IRrY55YNYhI5Svuqaoz7GXh5Z98pJ5IJRzx6mnlvZt7MiU79fVoNAvpF+uvmBkoMm2uUrNZuZ+sm9OnspdW5o8MvvNIA+bak52IA+V6c3hzbGxy7nLQ0O7JBuxVJdgXysUQhUo3y+Xk6Ll4fGb3oGmnNUjtWGP3cyRasepeQl+10oeUAVNyZsr9UAYCnl1s2sYspcc/Vp6JBuqMeclj9isnJCBQ/g3duM6WkmNQbPMXYpLBC+kOxv7ckicUzIzhfq19MjlgXTnVMGsr0Uihzoo4DdXwIM8OCAPECGvfgMK5AEAC+QBAAvkAQAL5AEAC+QBAAvkAQAL5AEAC+QBAAvkAQAL5AEAC+QBAAvkAQAL5AEAC+QBAAvkAQAL5AEAC+QBAAvkAQAL5AEAC+QBAMf/Af478HKwKQaJAAAAAElFTkSuQmCC" alt="" />

通过上面的图我们认识到了,step1按着顺序先执行,而由于第一个线程要执行3秒,这时step2被并行执行,3秒后,step1的第二个线程继续执行(由于使用了await,所以step1内部进行了等待,不会应响他外面的方法,也应响不了,呵呵!

怎么了,看了上面的例如,是不是对并行编程有了新的认识呢!

返回目录

上一篇:Java学习疑惑(8)----可视化编程, 对Java中事件驱动模型的理解


下一篇:OpenStack 企业私有云的若干需求(2):自动扩展(Auto-scaling) 支持