同步編程編程
建立類異步
using System; using System.Diagnostics; namespace TestAsyncConsole { public class NormalClass { Stopwatch sw = new Stopwatch(); public void DoSomething() { const int largeNumber = 600000; sw.Start(); int t1 = CountChar(1,largeNumber); int t2 = CountChar(2,largeNumber); LongProcess(largeNumber); LongProcess(largeNumber); LongProcess(largeNumber); Console.WriteLine("1: {0}",t1); Console.WriteLine("2: {0}",t2); } private int CountChar(int id,int Number) { int Total = 0; Console.WriteLine("開始調用{0} :{1,4} ms",id,sw.Elapsed.TotalMilliseconds); for (int i = 0; i < Number;i++ ) { Total += i; } Console.WriteLine("結束調用{0} :{1,4} ms",id,sw.Elapsed.TotalMilliseconds); return Total; } private void LongProcess(int largeNumber) { for(int i=0;i<largeNumber;i++) { } Console.WriteLine(" 時長: {0,4} 毫秒",sw.Elapsed.TotalMilliseconds); } } }
調用該類async
class Program { static void Main(string[] args) { NormalClass normal = new NormalClass(); normal.DoSomething(); Console.ReadLine(); } } }
獲得結果異步編程
異步編程spa
using System; using System.Diagnostics; using System.Threading.Tasks; namespace TestAsyncConsole { public class AsyncClass { Stopwatch sw = new Stopwatch(); public void DoSomething() { const int largeNumber = 600000; sw.Start(); var t1 = CountChar(1, largeNumber); var t2 = CountChar(2, largeNumber); LongProcess(largeNumber); LongProcess(largeNumber); LongProcess(largeNumber); Console.WriteLine("1: {0}", t1.Result); Console.WriteLine("2: {0}", t2.Result); } private async Task<int> CountChar(int id, int Number) { int Total = 0; Console.WriteLine("開始調用{0} :{1,4} ms", id, sw.Elapsed.TotalMilliseconds); Total = await Task.Run(()=> { for (int i = 0; i < Number; i++) { Total += i; } return Total; } ); Console.WriteLine("結束調用{0} :{1,4} ms", id, sw.Elapsed.TotalMilliseconds); return Total; } private void LongProcess(int largeNumber) { for (int i = 0; i < largeNumber; i++) { } Console.WriteLine(" 時長: {0,4} 毫秒", sw.Elapsed.TotalMilliseconds); } } }
調用該異步類獲得的結果以下pwa
能夠看到雖然代碼中LongProcess都在調用方法CountChar以後,可是實際執行的結果順序卻不是按照代碼中的順序。線程
總結異步同步編程的差別code