Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await’ operator to the result of the call

This C# warning occurs if you call an async method from your non-async code.

Imagine you have this imaginary async method:

internal class QueueRepository
{
  public async Task AddMessage<T>(T message)
  {
    await _mock.AddMessageAsync(message);
  }
}

And you call the method from this imaginary non-async method:

QueueRepository rep = new QueueRepository();
rep.AddMessage("hello world");

The compiler will warn you with the following message:

Warning CS4014 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await’ operator to the result of the call.

In this case, the compiler is just being nice, telling you that the async code will run in its own thread, and the code calling the method is continuing to run alongside.

But if you follow the compiler’s suggestion, and add the ‘await’ operator, you get a compiler error:

Error CS4032 The ‘await’ operator can only be used within an async method. Consider marking this method with the ‘async’ modifier and changing its return type to ‘Task<IActionResult>’.

So what can you do?

SOLUTION 1: WAIT FOR THE METHOD

If you wish to wait for the method to finish before continuing, you can call .Wait():

QueueRepository rep = new QueueRepository();
rep.AddMessage("hello world").Wait();

SOLUION 2: FIRE AND FORGET

You are the grown up here, you would actually like to have the method run asynchronously. You can ignore the warning, or add the secret discards ‘_ = ‘ return variable:

QueueRepository rep = new QueueRepository();
_ = rep.AddMessage("hello world");

With the _ = return variable, you tell the compiler to leave you alone you know what you are doing. Please note that you need C# 7.0 for the discards to work.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET, Microsoft Azure and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.