Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this TPL idiom exist?

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?

like image 577
Kent Boogaart Avatar asked Jan 24 '12 16:01

Kent Boogaart


2 Answers

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.

like image 177
Nick Butler Avatar answered Sep 23 '22 15:09

Nick Butler


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.

like image 42
Rich O'Kelly Avatar answered Sep 24 '22 15:09

Rich O'Kelly