class program
{
static vod Main(string[] args)
{
Console.WriteLine("Main() Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);
AsyncHandler();
// 打印AsyncHandler()函数在Main()中已经执行完毕的信息
Console.WriteLine("Handler Finished in Main!");
// AsyncHandler()在实际执行完成之前就返回了,需要阻塞主线程等待AsyncHandler()真正执行完毕
Console.ReadLine();
}
static async Task<int> Async() => await Task.Run<int>(() =>
{
// 线程ID与Handler()方法不同
Console.WriteLine("Async() Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.WriteLine("Async: Run{0}", i);
}
Console.WriteLine("Over");
return 666;
});
static async void AsyncHandler()
{
// 方法体中的内容实际为同步执行,与Main()函数线程ID相同
Console.WriteLine("Handler() Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);
// 调用异步方法Async()不会阻塞,Async()方法开始异步执行
Task<int> task = Async();
// 每隔0.1s打印输出,此时异步方法Async()也在另一线程中执行,同步打印输出
for (int i = 0; i < 3; i++)
{
Thread.Sleep(100);
Console.WriteLine("Handler: Run{0}", i);
}
// 在使用await之前的代码都运行在与Main()函数相同的线程
Console.WriteLine("Handler1() Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);
// AsyncHandler()中的循环执行3次,此时异步方法Async()尚未执行完毕,使用await关键字会阻塞函数
// 在Main()函数中,从调用await开始,AsyncHandler()就已返回了
Console.WriteLine(await task);
// 使用await之后的代码运行在Async()方法所处的线程
Console.WriteLine("Handler2() Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);
// 打印AsyncHandler()函数真正执行完毕信息
Console.WriteLine("Handler Really Finished!");
}
}
async/await
最新推荐文章于 2024-03-27 10:43:27 发布