Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress warning from empty async method

Let's just go ahead and say I have the following function:

public class Test {     public async Task Finalize()     {         // We don't need this in this class, so empty body     }      /*      * Additional methods snipped      */ } 

While this works just fine, I will get a compiler warning saying:

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

What would be the best way to circumvent this warning without modifying the method too much? In this case, I'm not able to throw an exception, since the method will get called, but absolutely nothing is bound to happen at this point, since the class I'm talking about has nothing to finalize.

like image 313
Eisenhorn Avatar asked Jan 16 '14 07:01

Eisenhorn


People also ask

What happens if async method is called without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

How do I return empty await?

You can either make the function async and leave off the return statement or have an empty return statement, or you can use return Promise. resolve( ); whether or not you make it async.

Can I use async without await C#?

This is possible. The async modifier tells the program that this is an asynchronous operation. Awiat will suspend the execution of the code in async, wait for the result after the await expression, skip the async function, and continue executing the following code. Alternatively, you can use Task instead.


2 Answers

This way will prevent the compiler warning instead of muting it:

For anybody interested, if you ever need to circumvent such a compiler warning:

public async Task DoStuff {     // This method should stay empty     // Following statement will prevent a compiler warning:     await Task.FromResult(0); } 
like image 180
Eisenhorn Avatar answered Sep 28 '22 08:09

Eisenhorn


before .Net 4.6 we had to return a dummy value which we do not need. However, now we can do it like this:

public async Task MyFunctionAsync() {     // Some work here...     await Task.CompletedTask; } 

Or of course, yet better, remove the async and await keywords from the code here, because async is not part of the the interface contract:

public Task MyFunctionAsync() {     // Some work here...     Task.CompletedTask; } 
like image 29
Mohammed Noureldin Avatar answered Sep 28 '22 09:09

Mohammed Noureldin