Using TPL with .NET 4, I'm trying to decide how to design APIs that deal with futures. One possibility that occurred to me was to mimic the async pattern but without an End(IAsyncResult)
method:
public Task<int> BeginGetAge()
{
// create and return task
}
public int GetAge()
{
return this.BeginGetAge().Result;
}
As such, callers can decide whether to call the blocking or non-blocking version of GetAge()
. Moreover, they have access to the future so can construct continuations on top of it etcetera.
Is this idiom valid? Are there any obvious drawbacks or problems that I'm missing? Does it perhaps even have an official name?
Returning a Task
is the new C#5 async way - it's called the TAP: Task-based Asynchronous Pattern.
The only difference is that the method is named GetAgeAsync
.
So, yes - this approach is recommended as it will make it easy to port to C#5 async when it is released.
This idiom seems perfectly valid to me and indeed support for Task
based asynchrony will be a big feature in upcoming versions of .Net.
However, I would change your implementation so the blocking method GetAge
does not call the async method and then wait for it - the overhead in (potentially) creating a new thread is unnecessary.
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