If I have an interface such as:
using System.Threading.Tasks;
...
public interface IFoo
{
Task doIt();
Task<bool> doItAndReturnStuff();
}
and one of the classes implementing this interface just happens to not require async methods, how can i correct override these functions?
In other words, how do I correctly return "void" and "bool" wrapped in Task objects?
For example:
public class FooHappensToNotNeedAsync : IFoo
{
public override Task doIt()
{
// If I don't return anything here, I get
// error that not all code paths return a value.
// Can I just return null?
}
public override Task<bool> doItAndReturnStuff()
{
// If I want to return true, how to I do it?
// This doesn't work:
return true;
}
}
NOTE - I can't strip the Task stuff completely because some of the classes that implement this interface are in fact asynch.
Thanks
Async void methods can wreak havoc if the caller isn't expecting them to be async. When the return type is Task, the caller knows it's dealing with a future operation; when the return type is void, the caller might assume the method is complete by the time it returns.
A Task returning async method can be awaited, and when the task completes, the continuation of the task is scheduled to run. A void returning async method cannot be awaited; it is a "fire and forget" method. It does work asynchronously, and you have no way of telling when it is done.
The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.
Async, Await And Asynchronous Programming In MVC. Async keyword is used to call the function/method as asynchronously. Await keyword is used when we need to get result of any function/method without blocking that function/method.
It's not clear what you're trying to achieve, but one approach (which would look the most like "normal" code) is probably just to make them async methods anyway:
public async Task DoIt()
{
// No-op
}
public async Task<bool> DoItAndReturnStuff()
{
return true;
}
Without any await
expressions, the method will complete synchronously anyway. You'll get a warning on each method, but you could disable that just for this piece of code using a #pragma
.
Alternatively - and I guess more simply in terms of not requiring a #pragma
to disable warnings - would be to use Task.FromResult
:
public Task DoIt()
{
// Returns a Task<bool>, but that's okay - it's still a Task
return Task.FromResult(true);
}
public Task<bool> DoItAndReturnStuff()
{
return Task.FromResult(true);
}
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