【发布时间】:2015-12-22 06:47:32
【问题描述】:
考虑以下方法:
private async Task<Task<Response>> SendAsync(string data)
{
this.Tcs = new TaskCompletionSource<Response>();
await this.Stream.WriteAsync(...);
await this.Stream.FlushAsync();
return this.Tcs.Task;
}
我有一个异步方法,我希望它返回Task<Response>。但是由于我想返回TaskCompletionSource<Response>(它在其他地方设置,所以我不能在这里等待它),我实际上必须返回Task<Task<Response>>。
在调用代码中,我有两种处理方法,同时将这种丑陋隐藏在类的外部。假设响应不重要并且可以忽略,我可以简单地返回一个Task:
public Task GetAsync(string key)
{
return this.SendAsync("GET " + key);
}
另一方面,如果我想要响应,我必须使用这个丑陋的await await 来使其工作:
public async Task<Response> GetAsync(string key)
{
return await await this.SendAsync("GET " + key);
}
有没有更好的方法来处理这个问题,即从SendAsync()返回Task<Response>而不在课堂外暴露Task<Task<Response>>,同时不使用await await?
【问题讨论】:
-
在
SendAsync中,而不是return this.Tcs.Task;为什么不使用return await this.Tcs.Task;来获得干净的Task<Response>返回类型? -
这确实是一个看起来很奇怪的
async方法,但既然您询问了关于解开Task<Task<T>>的问题,这正是Unwrap扩展方法(在System.Threading.Tasks.TaskExtensions中定义)所做的。
标签: c# .net async-await task-parallel-library task