Why doesn't my async method run until I close the program in C# console app? [duplicate]
![Why doesn't my async method run until I close the program in C# console app? [duplicate]](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2F80wy3gkl%2Fproduction%2F54e30bbcb677f725db7afda2ea2f51db97c37e46-1201x631.png%3Fh%3D1000&w=3840&q=75)
I'm trying to use async/await in a simple C# console app, but it doesn't seem to work as expected.
Here's a sample of my code:
static async Task Main(string[] args)
{
DoSomethingAsync();
Console.WriteLine("Done");
}
static async Task DoSomethingAsync()
{
await Task.Delay(2000);
Console.WriteLine("Finished async work");
}
When I run this, it prints "Done" immediately, and the async method doesn't seem to run unless I keep the console open. What am I doing wrong?
Answer
The issue was that I wasn’t await
-ing the async method in Main
. Since DoSomethingAsync()
returns a Task, and I didn’t await it, the program just moved on and printed "Done" without waiting for the async part to finish.
Here’s the fixed version:
static async Task Main(string[] args)
{
await DoSomethingAsync();
Console.WriteLine("Done");
}
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles