KDecker KDecker - 1 year ago 135
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

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

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

Task<String> FooBar();

Is the proper way to do this with
? 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
function. But I do admit the bolded question does equate to the duplicate question.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download