I have an interface
interface IFoo
{
Task<Bar> CreateBarAsync();
}
There are two methods to create Bar
, one asynchronous and one synchronous. I want to provide an interface implementation for each of these two methods.
For the asynchronous method, the implementation could look like this:
class Foo1 : IFoo
{
async Task<Bar> CreateBarAsync()
{
return await AsynchronousBarCreatorAsync();
}
}
But HOW should I implement the class Foo2
that uses the synchronous method to create Bar
?
I could implement the method to run synchronously:
async Task<Bar> CreateBarAsync()
{
return SynchronousBarCreator();
}
The compiler will then warn against using async
in the method signature:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
Or, I could implement the method to explicitly return Task<Bar>
. In my opinion the code will then look less readable:
Task<Bar> CreateBarAsync()
{
return Task.Run(() => SynchronousBarCreator());
}
From a performance point of view, I suppose both approaches have about the same overhead, or?
Which approach should I choose; implement the async
method synchronously or explicitly wrap the synchronous method call in a Task
?
EDIT
The project I am working on is really a .NET 4 project with async / await extensions from the Microsoft Async NuGet package. On .NET 4, Task.Run
can then be replaced with TaskEx.Run
. I consciously used the .NET 4.5 method in the example above in the hope of making the primary question more clear.
question from:
https://stackoverflow.com/questions/26751581/how-to-implement-interface-method-that-returns-taskt 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…