What can I do when I have an interface that returns a task (void) but one of the implementations has no async action?
My interface IDatabaseService has two implementations: FirestoreDatabaseService and CacheDatabaseService. It makes sense for FirestoreDatabaseService to use the Method async Task AddResult(ResultDto result) as result of a method but the CacheDatabaseService has only a list and needs no await, it is basically a void method.
I get a warning
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(...)'" when I implement the method in CacheDatabaseService async. If I remove the async I have to return a task but Task.FromResult does not work for void Tasks.
That warning almost always means your method should not be async.
The async keyword really just enables the use of await. So if you aren't using await, you don't need async.
If AddResult must return a Task, then return a Task. If you aren't actually doing anything asynchronous, then you can return Task.CompletedTask.
For example:
public Task AddResult(ResultDto result) {
    ...
    return Task.CompletedTask;
}
If you have to return a value (Task<T>), then you can use Task.FromResult().
An interface that specifies that a method should return a Task is just a way of making it possible to make the method async. It doesn't mean it must.
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