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.
You can put the following directive on the file(s):
#pragma warning disable 1998
However, I'd recommend leaving the warning alone, and taking its advice. It's a warning for a good reason ;)
EDIT: if you want to disable the warning for just one method, you can do this:
#pragma warning disable 1998
async Task Foo() {}
#pragma warning restore 1998
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);
}
async
and the await
from the above answer and it'll match the same signature and not generate a bunch of pointless code that won't be optimised away. - Jon Hanna
This is a somewhat common problem when you have a synchronous (or noop) implementation for an asynchronous interface.
You can implement a Task
-returning method without the async
keyword by just returning a completed Task
, as such:
public Task FinalizeAsync()
{
return Task.FromResult(0);
}
However, this still allocates a Task
every time it's called. If you find yourself doing this a lot, you may want to cache a completed Task
instance. My AsyncEx library provides a number of task constants for this purpose:
public Task FinalizeAsync()
{
return TaskConstants.Completed;
}
Finally, you may want to take a look at my blog post on asynchronous disposal for a couple of alternative approaches.
async
is not part of the actual signature of a method, and therefore calling code and matching of interfaces won't be affected, that'd make it perfect ;) - Jon Hannaasync
. - Toby J
before .Net 4.6 we had to return a dummy value which we do not need to do this. However, now we can do it like this:
public async Task MyFunctionAsync()
{
// Some works here...
await Task.CompletedTask;
}
Remove "async" and the warning goes away:
public class Test
{
public void Finalize()
{
// We don't need this in this class, so empty body
}
}
async
,public
cannot be used withinterfaces
- Sriram Sakthivel