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):
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:
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 theasync
keyword by just returning a completedTask
, as such: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 completedTask
instance. My AsyncEx library provides a number of task constants for this purpose:Finally, you may want to take a look at my blog post on asynchronous disposal for a couple of alternative approaches.
This way will prevent the compiler warning instead of muting it:
For anybody interested, if you ever need to circumvent such a compiler warning:
before .Net 4.6 we had to return a dummy value which we do not need. However, now we can do it like this:
Remove "async" and the warning goes away: