首页 > 解决方案 > C# await delay not working

问题描述

I want to pause the program so it does not close. I have a code running in the main thread. Tried this way, but this code instantly skips and the program closes instead of waiting.

How can I make it wait for the WaitMy method to complete?

    static void Main(string[] args)
    {
        //any code here...
        Console.WriteLine("Discovery started");

        WaitMy();
    }

    private async static void WaitMy()
    {
        //await Task.Delay(30 * 1000);
        await Task.Run(async () => await Task.Delay(30 * 1000));
    }

The application runs with .net 4.5.

标签: c#async-await

解决方案


Change the code to following to make it work:

static async Task Main(string[] args)
{
    //any code here...
    Console.WriteLine("Discovery started");

    await WaitMy();
}

How this works ?

  1. You need C# 7.1 or later versions
  2. Now Main method can be declared async and has return type as Task for introducing await
  3. It will simply let the delay execute asynchronously, but will renter the main context for continuation, which will not exit

Another suggestion would be, you just need await Task.Delay(30 * 1000), wrapping inside the Task.Run is not required here


推荐阅读