.NET Core 的异步编程-只讲干货(async,await,Task)
namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine(ThreadID() + " =》主线程启动"); MethodAsync();//调用异步方法 Console.WriteLine(ThreadID() + " =》主线程继续执行"); Console.WriteLine(ThreadID() + " =》主线程结束 END"); Console.Read(); } static async void MethodAsync() { Console.WriteLine(ThreadID() + " =》MethodAsync方法开始执行"); string str = await DoSomething();//等待GetString执行完成 Console.WriteLine(ThreadID() + " =》MethodAsync方法执行结束"); } static Task<string> DoSomething() { Console.WriteLine(ThreadID() + " =》DoSomething方法开始执行"); return Task<string>.Run(() => { Thread.Sleep(4000);//导步线程 处理耗时任务 Console.WriteLine(ThreadID() + " =》DoSomething方法结束执行"); return "GetString的返回值"; }); } static string ThreadID() { return Thread.CurrentThread.ManagedThreadId.ToString(); } } }
1 =》主线程启动
1 =》MethodAsync方法开始执行
1 =》DoSomething方法开始执行
1 =》主线程继续执行
1 =》主线程结束 END
7 =》DoSomething方法结束执行
public class AsyncAwaitTest { public void Start() { Console.WriteLine($"aaa,线程Id:{Thread.CurrentThread.ManagedThreadId}"); AsyncMethod(); Console.WriteLine($"eee,线程Id:{Thread.CurrentThread.ManagedThreadId}"); Console.ReadLine(); } public async Task<bool> AsyncMethod() { Console.WriteLine($"bbb,线程Id:{Thread.CurrentThread.ManagedThreadId}"); await Task.Run(() => { Thread.Sleep(500); Console.WriteLine($"ccc,线程Id:{Thread.CurrentThread.ManagedThreadId}"); }); Console.WriteLine($"ddd,线程Id:{Thread.CurrentThread.ManagedThreadId}"); return true; } }
aaa,线程Id:1
bbb,线程Id:1
eee,线程Id:1
ccc,线程Id:7
ddd,线程Id:7
(21条消息) .Net Core中无处不在的Async/Await是如何提升性能的?_.net core async await_BINGHANYULENG的博客-CSDN博客