Why Does a C# Async Method Return Before Its Work Is Finished?

Asked 6 days ago 88 views

0

I’m trying to understand what actually happens when an asynchronous method is called without await. In this small example, the message in Main can appear before SaveAsync finishes:

static async Task Main()
{
    SaveAsync(); // Starts the operation, but Main does not wait for it.
    Console.WriteLine("Main finished"); // This may print before SaveAsync completes.
}

static async Task SaveAsync()
{
    await Task.Delay(1000); // Simulates work that completes asynchronously.
    Console.WriteLine("Save finished"); // May run after Main has continued.
}

Is this simply a case of forgetting await, or are there situations where starting a task without waiting is intentional? I’m also unsure what happens to that unfinished work if the application exits.

0 Answers


Write Your Answer