re: C# Async Await, Simply VIEW POST

FULL DISCUSSION
 

If you starting a new Task.Run or having a Task in a method without something to do after it, you don't need to async/await it in the method.

Example, instead of:

public static async Task<int> MakeOneMillionDollars()
{
    return await Task.Run(() =>
    {
        Console.WriteLine("Million Dollars Made!");
                return 1000000;
    });
}

you can just write this:

public static Task<int> MakeOneMillionDollars()
{
    return Task.Run(() =>
    {
        Console.WriteLine("Million Dollars Made!");
        return 1000000;
    });
}

This removes some async/await overhead :)

Also as already mentioned Task.Delay instead of Thread.Sleep

 

Good point, but also it should always be taken with great care in production scenarios that utilize try/catch in similar code as now you are risking of not having the exception unwrapped in the MakeOneMillionDollars due to not awaiting it here explicitly. But the perf tip is on point as this code will produce one compiler generated type less with its following state machine.

code of conduct - report abuse