当async-await更改线程时?
在test2()方法中,完成方法所需的时间甚至比test1()
更长 [Route("api/[controller]")]
[HttpGet]
public async Task<IActionResult> Get()
{
await MainAsync();
return new ObjectResult(null);
}
static async Task MainAsync()
{
Console.WriteLine("Main Async: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
await test1();
//await test2();
// . . .more code
}
private static async Task test1()
{
Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
await Task.Delay(1);
Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
}
private static async Task test2()
{
Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
System.Threading.Thread.Sleep(5000);
await Task.FromResult(0);
Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
}
答案 0 :(得分:6)
test1
等待Task.Delay(1)
,不将在等待它时完成,这意味着test1
的其余部分需要安排为延续。
对于test2
,您等待Task.FromResult
,这将始终返回已完成的Task
。当await
已经完成的任务时,该方法可以继续在当前线程上运行,而无需安排延续。