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.
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.
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.
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.
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); }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With