C# async await的使用
2021-06-09 02:03
标签:new void fun line bsp 线程 string wait for async 声明一个包含异步代码的函数,该函数执行时不会阻塞调用线程。 async标记的函数返回值必须为 void ,Task,Task await 必须修饰Task 或者Task 典型代码 全部代码 输入内容 C# async await的使用 标签:new void fun line bsp 线程 string wait for 原文地址:https://www.cnblogs.com/noigel/p/10669753.html public static async Taskint> CalAsync()
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine("当前位置async函数,await之前,线程ID"+tid);
int result = await Task.Run(new Funcint>(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);
Taskint> t = CalAsync();
Console.WriteLine("当前位置主函数,调用async异步之后,线程ID" + tid);
Console.Read();
}
public static async Taskint> CalAsync()
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine("当前位置async函数,await之前,线程ID"+tid);
int result = await Task.Run(new Funcint>(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;
}
}
上一篇:C#基础-hashtable