1. 使用async标记的方法被认为是一个异步方法,如果不使用await关键字,调用跟普通方法没有区别
static async Task Main(string[] args)
{
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
TestAwait();
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
}
private static async Task TestAwait()
{
Console.WriteLine("执行线程id:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000); //模拟耗时操作
Console.WriteLine("执行完线程id:" + Thread.CurrentThread.ManagedThreadId);
}
执行结果:
2.当使用await关键字时,异步方法会暂时挂起,让出当前线程的控制权,而不会阻塞线程。当被await的异步操作完成后,异步方法会恢复执行,并返回结果。
在大多数情况下,异步操作并不会创建新的线程,而是通过利用I/O完成端口或其他异步机制来实现异步操作。这样可以避免创建额外的线程,提高程序的性能和资源利用率。
static async Task Main(string[] args)
{
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
TestAwait();
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Hello, World!");
Console.ReadLine();
}
private static async Task TestAwait()
{
Console.WriteLine("执行线程id:" + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("执行完线程id:" + Thread.CurrentThread.ManagedThreadId);
}
3.使用task.result获取执行结果,会阻塞调用线程
static async Task Main(string[] args)
{
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
int a = TestAwait().Result;
Console.WriteLine("主线程id:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Hello, World!");
Console.ReadLine();
}
private static async Task<int> TestAwait()
{
Console.WriteLine("执行线程id:" + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("执行完线程id:" + Thread.CurrentThread.ManagedThreadId);
return 1;
}