An async method with await vs A normal method that returns a Task

Viewed 207

In the following program:

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task f()
    {
        void action()
        {    
            Thread.Sleep(100);
            Console.WriteLine("4");
            Thread.Sleep(100);
        }
        await Task.Run(action);
    }
    static async void g()
    {
        Thread.Sleep(100);
        Console.WriteLine("1");
        Console.WriteLine("2");
        await f();
        Console.WriteLine("5");
    }
    static void Main()
    {
        g();
        Console.WriteLine("3");
        Console.ReadKey();
    }
}

I can change the function f and write it as:

static Task f()
{
    void action()
    {
        Thread.Sleep(100);
        Console.WriteLine("4");
        Thread.Sleep(100);
    }
    return Task.Run(action);
}

The output doesn't change. Which is preferred? an async f with await or a normal f that returns a Task?

Edit: The output for both cases:

 1
 2
 3
 4
 5
1 Answers

Ok, Nice question. Let me explain you, In case you have used async void and the method throws some Exception as this process is done without awaiting the system will fail to handle the exception and the process terminates the application.

It is always advisable to use async Task or async Task<bool> or async Task<int> just await the method while calling to check every happened well or not.

It is bad practice to us async void

Related