Program exits upon calling await

Your problem is that await returns the control flow of the program to the caller of the function. Normally execution is continued at that point when the asynchronous task you await finishes.

So control is returned to your main function as you wait for printMessage and main now waits for a key input. As you hit the key main returns to the OS and your process (including all asynchronous tasks) terminates.

Change your InitializeMessageSystem to

private async Task InitializeMessageSystem ( )  

and change the code in main to

InitializeMessageSystem().Wait();

to wait until InitializeMessageSystem finishes completely before waiting for the key.


The below code executes without any errors or warnings. But when you execute the code the program exits silently. What you might be expecting is the program waits for the task to complete, asks the user to press any key and exit. What actually happens is after the await statement is executed the control goes back to the invoking step. In our case after the step await task; is executed, before the task completes the control goes back to the invoking step SomeTask(); and the program exits.

class Program
{
    static void Main(string[] args)
    {
        SomeTask();
    }

    public static async void SomeTask()
    {
        Task task = Task.Run(() =>
        {
            System.Threading.Thread.Sleep(20000);
            Console.WriteLine("Task Completed!");
        });
        await task;
        Console.WriteLine("Press any key to exit");
        Console.ReadLine();
    }
}

To fix this, add await to the SomeTask(); call so that the program waits for async SomeTask() to complete. You should also change the return type of SomeTask() from void to Task.

class Program
{
    static void Main(string[] args)
    {
        await SomeTask();
    }

    public static async Task SomeTask()
    {
        Task task = Task.Run(() =>
        {
            System.Threading.Thread.Sleep(20000);
            Console.WriteLine("Task Completed!");
        });
        await task;
        Console.WriteLine("Press any key to exit");
        Console.ReadLine();
    }
}

Tags:

C#

Async Await