Quantcast
Channel: briancaos – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 276

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

$
0
0

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:


Viewing all articles
Browse latest Browse all 276

Trending Articles