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]
typescript
Ethan Jackson

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"); }

Related Articles