async,await与task.wait()或task.Result的区别
你是否曾经与我一样不理解async,await与task.wait()或者task.Result的区别?
接下来,一个Demo让你看出他们之间的区别。
static void Main(string[] args) { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:start"); Test(); //不等待 Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:end"); Console.Read(); } static Task<int> Sleep() { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep start"); Thread.Sleep(1000); Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep end"); return Task.FromResult(100); } static Task<int> Test() { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test start"); var a=Task.Run(Sleep).Result;//由上一篇文章可知Run将会在线程池内调度执行 Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test end"); return Task.FromResult(a); }
运行结果:
1:start
1:Test start
4:Sleep start
4:Sleep end
1:Test end
1:end
由此可以看出Task.Result会阻塞主线程。
static void Main(string[] args) { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:start"); TestAsync();//不等待 Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:end"); Console.Read(); } static Task<int> Sleep() { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep start"); Thread.Sleep(1000); Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep end"); return Task.FromResult(100); } static async Task<int> TestAsync() { Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test start"); var a = await Task.Run(Sleep); Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test end"); return a; }
运行结果:
1:start
1:Test start
4:Sleep start
1:end
4:Sleep end
4:Test end
async,await不会阻塞主线程