如何在异步方法中休眠或阻止执行。Thread.Sleep 不起作用

Bla*_*man -1 c# async-await

我有一个异步方法,其签名如下:

public static async void Run(..)
{
  //..
  var responseMessage = await client.PostAsync(..);
  // ..
   using (Stream stream = await responseMessage.Content.ReadAsStreamAsync())
   //...

   Thread.Sleep(5000);
}
Run Code Online (Sandbox Code Playgroud)

我可以在控制台应用程序中使用此方法,如下所示:

 static async Task Main(string[] args)
 {
     for(int x = 1; x < 100; x++)
     {
        Run(...);
     }  
 }
Run Code Online (Sandbox Code Playgroud)

由于速率限制,我想在我的 Run 方法中阻塞/休眠,我该怎么做?

我试过这个:

 public static async void Run(...)
    {
      // ...
       Thread.Sleep(5000);
    }
Run Code Online (Sandbox Code Playgroud)

但这似乎没有任何作用。有人可以解释为什么这不起作用以及正确的方法吗?

Sea*_*ean 5

使用模式时需要使用Task.Delayasync

static async Task Main(string[] args)
{
   for(int x = 1; x < 100; x++)
   {
      await Run(...);
   }  
}

public static async Task Run(...)
{
  // ...
  await Task.Delay(5000);
}
Run Code Online (Sandbox Code Playgroud)

注意:我还更改了您的Run方法,async以便可以等待。此外,async void通常是一个坏主意,通常只应在编写事件处理程序时完成。

  • @Blankman - 这就是将会发生的事情。“Run”上的等待意味着循环的下一次迭代在“Run”完成之前不会发生。 (2认同)