1,,用同步编码的形式编写异步程序
namespace AwaitAsyncLibrary { /// <summary> /// await/async:是个新语法,是个语法糖, /// 不是一个全新的异步多线程使用方式 /// (语法糖:就是编译器提供的新功能) /// 本身并不会产生新的线程,但依托于Task而存在, /// 所以程序执行时,也是有多线程的 /// </summary> class AwaitAsyncClassNew { public void Show() { Console.WriteLine($"This Show start {Thread.CurrentThread.ManagedThreadId}"); { //this.NoReturn(); } { this.ReturnTask(); } Console.WriteLine($"This Show end {Thread.CurrentThread.ManagedThreadId}"); } /// <summary> /// 没有返回值---在方法俩面开启了一个Task 线程 /// </summary> /// <returns></returns> public void NoReturn() { Console.WriteLine($"This Noreturn start {Thread.CurrentThread.ManagedThreadId}"); Task task = Task.Run(() => { Console.WriteLine($"This Noreturn Task start {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(2000); Console.WriteLine($"This Noreturn Task end {Thread.CurrentThread.ManagedThreadId}"); }); Console.WriteLine($"This Noreturn end {Thread.CurrentThread.ManagedThreadId}"); task.ContinueWith(t => { Console.WriteLine($"This Noreturn end " + $" {Thread.CurrentThread.ManagedThreadId}"); }); } public async Task ReturnTask() { Console.WriteLine($"This Noreturn start {Thread.CurrentThread.ManagedThreadId}");//调用线程执行 Task task = Task.Run(() => { Console.WriteLine($"This Noreturn Task start {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(2000); Console.WriteLine($"This Noreturn Task end {Thread.CurrentThread.ManagedThreadId}"); //子线程执行 });//调用线程发起,子线程执行 await task;//调用线程回去忙自己的事 Console.WriteLine($"This Noreturn end " + $" {Thread.CurrentThread.ManagedThreadId}");//子线程执行,如果没有await, //应该是调用线程执行 //可以认为,加了await就等同于将await后面的代码包装成一个回调 } } }
1