将 TPL 与 .NET 4 结合使用,我试图决定如何设计处理 future 的 API。我想到的一种可能性是模仿异步模式,但没有 End(IAsyncResult)
方法:
public Task<int> BeginGetAge()
{
// create and return task
}
public int GetAge()
{
return this.BeginGetAge().Result;
}
因此,调用者可以决定是调用阻塞版本还是非阻塞版本的 GetAge( )
。此外,他们可以访问未来,因此可以在其之上构建延续等等。
这个成语有效吗?我是否遗漏了任何明显的缺点或问题?它可能有正式名称吗?
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?
发布评论
评论(2)
返回
Task
是新的 C#5 异步方式 - 它称为 TAP:基于任务的异步模式。唯一的区别是该方法名为
GetAgeAsync
。所以,是的 - 建议使用这种方法,因为它可以在发布时轻松移植到 C#5 异步。
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.
这个习惯用法对我来说似乎完全有效,并且实际上对基于任务的异步的支持将是即将推出的 .Net 版本中的一个重要功能。
但是,我会更改您的实现,以便阻塞方法 GetAge 不会调用异步方法,然后等待它 - (可能)创建新线程的开销是不必要的。
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.