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.
TAP uses a single method to represent the initiation and completion of an asynchronous operation. This contrasts with both the Asynchronous Programming Model (APM or IAsyncResult ) pattern and the Event-based Asynchronous Pattern (EAP). APM requires Begin and End methods.
The BeginOperationName method begins asynchronous operation OperationName and returns an object that implements the IAsyncResult interface.
Naming ConventionBy convention, you append "Async" to the names of methods that have an async modifier. You can ignore the convention where an event, base class, or interface contract suggests a different name. For example, you shouldn't rename common event handlers, such as Button1_Click .
Async code can be used for both I/O-bound and CPU-bound code, but differently for each scenario. Async code uses Task<T> and Task , which are constructs used to model work being done in the background. The async keyword turns a method into an async method, which allows you to use the await keyword in its body.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With