在编写代码的时候,有时候我们需要“暂停一段时间,再继续执行代码”。比如调用一个Http接口,如果调用失败,则需要等待2秒钟再重试。
在异步方法中,如果需要“暂停一段时间”,那么请使用Task.Delay(),而不是Thread.Sleep(),因为Thread.Sleep()会阻塞主线程,就达不到“使用异步提升系统并发能力”的目的了。
如下代码是错误的:
public async Task TestSleep()
{
await System.IO.File.ReadAllTextAsync("d:/temp/words.txt");
Console.WriteLine("first done");
Thread.Sleep(2000);
await System.IO.File.ReadAllTextAsync("d:/temp/words.txt");
Console.WriteLine("second done");
return Content("xxxxxx");
}
上面的代码是能够正确的编译执行的,但是会大大降低系统的并发处理能力。因此要用Task.Delay()代替Thread.Sleep()。如下是正确的:
public async Task TestSleep()
{
await System.IO.File.ReadAllTextAsync("d:/temp/words.txt");
Console.WriteLine("first done");
await Task.Delay(2000);//!!!
await System.IO.File.ReadAllTextAsync("d:/temp/words.txt");
Console.WriteLine("second done");
return Content("xxxxxx");
}
作者:杨中科 https://www.bilibili.com/read/cv10566638 出处:bilibili