Suppose I am working on a C# library that is utilizing an interface with the following signature, say:
public interface IMyInterface
{
public void DoWork();
}
And I have 2 different classes implementing this interface.
- One that is only running synchronous code (so the
void
return type would be fine). - One that needs to await an async call (so, ideally, I'd want
DoWork
to beasync Task
, notvoid
).
The non-async class isn't a problem since it truly does only need a void
return type:
public class NonAsyncClass : IMyInterface
{
public void DoWork()
{
Console.WriteLine("This is a non-Async method");
}
}
But I am trying to think of the best way to implement the async
class. I am thinking of something like this:
public class AsyncClass : IMyInterface
{
public void DoWork()
{
var t = Task.Run(async () => {
await ExternalProcess();
});
t.Wait();
}
}
But it feels like it isn't the right way to do things.
What would be the best way to program against an interface (supposing you don't have control over changing any of the interface signatures) with a void
return type when the method needs to be async
? Or vice-versa, how does one program against a asyc Task
return type when the method doesn't have any asyncronous code?