Asynchronous software and virtual functions

If I have an interface, for example:

using System.Threading.Tasks; ... public interface IFoo { Task doIt(); Task<bool> doItAndReturnStuff(); } 

and one of the classes that implements this interface simply does not require the use of async methods, how can I fix the redefinition of these functions?

In other words, how to return "void" and "bool" to Task objects correctly?

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 cannot completely remove the Task material, because some classes implementing this interface are actually asynch.

thanks

+8
c # asynchronous windows-store-apps windows-runtime
source share
1 answer

It is not clear what you are trying to achieve, but one approach (which will be most similar to the "normal" code) is probably just to make them asynchronous methods:

 public async Task DoIt() { // No-op } public async Task<bool> DoItAndReturnStuff() { return true; } 

Without any await expressions, the method will end synchronously anyway. You will receive a warning for each method, but you can only disable it for this piece of code with #pragma .

Alternatively - and I suggest that it’s simpler in terms of not having #pragma turn off warnings β€” use Task.FromResult :

 public Task DoIt() { // Returns a Task<bool>, but that okay - it still a Task return Task.FromResult(true); } public Task<bool> DoItAndReturnStuff() { return Task.FromResult(true); } 
+15
source share

All Articles