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?
CodePudding user response:
When you cannot change interface, you should call it like this:
public void DoWork() {
// Start a task - calling an async function in this example
Task callTask = Task.Run(() => ExternalProcess());
// Wait for it to finish
callTask.Wait();
}
CodePudding user response:
If ExternalProcess return as void you cannot use await against void. Complier will tell you when try to complie code. Then problem is not occured because interface.
If ExternalProcess reuturn as "Task" datatype your code must be work fine.
Not clear in your sample code. You want to convert Async Operation to Synchronous? When user call DoWork method , program will be block until operation finish and continue doing next line of code.