简体   繁体   English

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

[英]How to sleep or block execution in a async method. Thread.Sleep doesn't work

I have an async method that has a signature like:我有一个异步方法,其签名如下:

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

   Thread.Sleep(5000);
}

I can this method inside of my console app like this:我可以在控制台应用程序中使用此方法,如下所示:

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

I want to block/sleep inside of my Run method because of rate limiting, how can I do this?由于速率限制,我想在我的 Run 方法中阻塞/休眠,我该怎么做?

I tried this:我试过这个:

 public static async void Run(...)
    {
      // ...
       Thread.Sleep(5000);
    }

But this didn't seem to do anything.但这似乎没有任何作用。 Can someone explain why this didn't work and the correct way?有人可以解释为什么这不起作用以及正确的方法吗?

You need to use Task.Delay when using the async pattern:使用async模式时需要使用Task.Delay

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

public static async Task Run(...)
{
  // ...
  await Task.Delay(5000);
}

NOTE: I've also changed your Run method to be async so that it can be awaited.注意:我还将您的Run方法更改为async以便可以等待。 Also, async void is generally a bad idea and should typically only be done when writing event handlers.此外, async void通常是一个坏主意,通常只应在编写事件处理程序时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM