Wait, I Don't Have to Await?

One thing I see quite often in asynchronous C# code is unnecessary awaits. I'm not sure if it is a lack of understanding of async/await in C# or if it is a product of example code making its way into production code. Take the following method for example:

public async Task RunProcessAsync()
{
    await Task.Delay(Random.Shared.Next(100, 1500));
}        

In this case nothing happens with the task itself other than awaiting it. This asynchronous call could be calculating a value, calling an API or any number of things. What the asynchronous call is or does, is not important. The important part is the return value of the asynchronous operation is never used in the method. The method simply returns the value of the asynchronous operation or simply returns after the asynchronous call.

Since an await keyword isn't free (an allocation occurs with every await and possibly a context switch), it's more efficient to rewrite the method as follows:

public Task RunProcessAsync()
{
    return Task.Delay(Random.Shared.Next(100, 1500));
}        

Notice the removal of the await keyword as well as the async keyword. The Task can simply be returned from the method, and the caller will await the returned Task. This prevents an unnecessary await, which results in one less allocation. When writing performant code, these small details matter, especially in hot paths in some environments.

To view or add a comment, sign in

Others also viewed

Explore topics