Say I have an interface
interface IFoo {
Task SomeMethodAsync();
}
And I wanted to implement this interface, but for one class the method is blank.
Should I live with the warning this produces?
async Task SomeMethodAsync() {}
Or should I have it return some dummy task?
async Task SomeMethodAsync() { await Task.Run(() => {}); }
Or is there another option?
Also I want to implement this method as an explicit interface method. Will that make any difference?
I ran into this with an abstract base class. I tried Stephen Cleary's method, but was getting compiler errors in C# 6.
An example of my base method:
protected abstract Task OnFoo(Bar bar);
This is what I had to do in my derived class:
protected override async Task OnFoo(Bar bar)
{
await Task.FromResult(true);
}
The problem with the other answer was the return
keyword in the phrase. Because the return value of Task
is essentially void
, you can't return anything. Also, the await
keyword is required.
Methods that return Task
do not have to be async
.
I would recommend something like this:
Task IFoo.SomeMethodAsync()
{
return Task.FromResult(true);
}
I'm assuming that if this was a synchronous method, you would just have an empty method body; this is the async
equivalent of an empty method body.
It depends only how do you decide that framework has to handle such cases.
You have, imo, several options :
raise an exception (will break immidiately execution, and you have to handle it in some way in some place in execution chain).
return default-value
(that can be a solution offered by you: just an empty task that doesn't do anything. Bad about this is that I call function expecting it does something, it doesn't notify me about anything but do not do anything either. Imo, this is bad design.
return some not-valid-value
, which intercepted by caller so caller "knows" that something is not ok.
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