KDecker KDecker - 3 months ago 11
C# Question

Proper way to await something in a method that does not return void, Task, or Task<T>?

Say I am implementing an interface with the method signature

String FooBar();


And later on I am implementing this interface in my class

public String FooBar()
{
return "";
}


But at some point I would like to
await
something

public async Task<String> FooBar()
{
await Task.Delay(500);
return "";
}


How can I
await
something in this scenario without having to alter the method signature to


Task<String> FooBar();


Is the proper way to do this with
Task.WaitAll
? Or is there a more accepted pattern?

EDIT: I do not feel that my question is an exact duplicate, though very much related, to How would I run an async Task<T> method synchronously? . I am more worried about how to implement the interface than I am about how to call the
async
function. But I do admit the bolded question does equate to the duplicate question.

I do see now it is more appropriate to return
Task
because of the possibility of implementors of the interface calling
async
methods. Otherwise I "lock them out" of doing so properly.

Answer

How can I await something in this scenario without having to alter the method signature

The proper solution is to alter the method signature. Any interface method that could be implemented asynchronously should return Task/Task<T>.

(From a design perspective, this is very similar to deciding whether an interface should derive from IDisposable - the interface has to predict its own implementation details).

As far as improper solutions go, this is just another variant of the "call async method from sync method" question. There is no ideal, universal, or commonly-accepted solution. There are only a few hacks you can do, each with different drawbacks. I cover these in my async brownfield article.

Comments