I've got an interface with some async functions. Some of the classes that implements the interface does not have anything to await, and some might just throw. It's a bit annoying with all the warnings.
When not using await in a async function.
Is it possible to suppress the message?
public async Task<object> test()
{
throw new NotImplementedException();
}
warning CS1998: 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.
In case you already link against Reactive Extension, you can also do:
Reactive and async/await are both amazing in and by themselves, but they also play well together.
Includes needed are:
Methods returning
Task
, I believe.async
is an implementation detail, so it can't be applied to interface methods.In these cases, you can take advantage of the fact that
async
is an implementation detail.If you have nothing to
await
, then you can just returnTask.FromResult
:In the case of throwing
NotImplementedException
, the procedure is a bit more wordy:If you have a lot of methods throwing
NotImplementedException
(which itself may indicate that some design-level refactoring would be good), then you could wrap up the wordiness into a helper class:The helper class also reduces garbage that the GC would otherwise have to collect, since each method with the same return type can share its
Task
andNotImplementedException
objects.I have several other "task constant" type examples in my AsyncEx library.
Another option, if you want to keep the body of the function simple and not write code to support it, is simply to suppress the warning with #pragma:
If this is common enough, you could put the disable statement at the top of the file and omit the restore.
http://msdn.microsoft.com/en-us/library/441722ys(v=vs.110).aspx
There is difference in different solutions which you can find in answers and strictly speaking you should know how caller is going to call the async method, but with default usage pattern that assumes ".Wait()" on method result - "return Task.CompletedTask" is the best solution.
Note:
FromResult
can't be directly compared.Test Code:
}
You can drop the async keyword from the method and just have it return Task;
It might be occured cs1998 below.
Then you can reform below.