'How to correctly implement a TAP method?
I want to provide a task-based asynchronous pattern-style method. When awaiting the method, I could not find any difference between these two ways of providing the method:
// GetStats is a delegate for a void method in this example
public Task GetStatsAsync()
{
return Task.Run(GetStats);
}
public async Task GetStatsAsync()
{
return await Task.Run(GetStats);
}
// Usage:
await GetStatsAsync();
// Difference?
The upper method seems to have less overhead than the lower one. When looking at the MSDN blogs, I noticed that they seem to use the lower method. (For example in this article)
Why? What exactly is the difference? They both seem to work.
Solution 1:[1]
Those are both logically the same, but the second one has more overhead and is not recommended for that reason.
You may find my async intro helpful, as well as the task based asynchronous pattern document.
For more information on the overhead of async, I recommend the Zen of Async by Stephen Toub.
You probably also want to read "Should I Expose Asynchronous Wrappers for Synchronous Methods?" In short, the answer is "no."
Solution 2:[2]
I was under the impression that the proper way of implementing a TAP pattern would be the following:
public Task<IResult> GetLongWindedTaskResult(){
var tcs = new TaskCompletionSource<IResult>();
try
{
tcs.SetResult(ResultOFSomeFunction());
}
catch (Exception exp)
{
tcs.SetException(exp);
}
return tcs.Task;
}
This way ensures that you correctly get an exception if thrown and it would make it easier to implement a cancel method if needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kevin B Burns |
