标签:new void fun line bsp 线程 string wait for
async 声明一个包含异步代码的函数,该函数执行时不会阻塞调用线程。
async标记的函数返回值必须为 void ,Task,Task<TResult>
await 必须修饰Task 或者Task<TResult>
典型代码
public static async Task<int> CalAsync() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之前,线程ID"+tid); int result = await Task.Run(new Func<int>(Cal)); tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之后,线程ID" + tid); return result; }
全部代码
class Program { static void Main(string[] args) { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置主函数,调用async异步之前,线程ID"+tid); Task<int> t = CalAsync(); Console.WriteLine("当前位置主函数,调用async异步之后,线程ID" + tid); Console.Read(); } public static async Task<int> CalAsync() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之前,线程ID"+tid); int result = await Task.Run(new Func<int>(Cal)); tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之后,线程ID" + tid); return result; } public static int Cal() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置耗时函数,线程ID"+tid); int sum = 0; for (int i = 0; i < 999; i++) { sum = sum + i; } Console.WriteLine("当前位置耗时函数完成,线程ID" + tid); return sum; } }
输入内容
标签:new void fun line bsp 线程 string wait for
原文地址:https://www.cnblogs.com/noigel/p/10669753.html