在异步方法中等待与 Task.Result
Await vs Task.Result in an Async Method
执行以下操作有什么区别:
async Task<T> method(){
var r = await dynamodb.GetItemAsync(...)
return r.Item;
}
对
async Task<T> method(){
var task = dynamodb.GetItemAsync(...)
return task.Result.Item;
}
在我的例子中,出于某种原因,只有第二个有效。第一个似乎永远不会结束。
task.Result is accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method。
一旦操作的结果可用,它就会被存储,并在随后对结果 属性 的调用中立即被 return 编辑。注意,如果任务运行过程中发生异常,或者任务被取消,Result属性不会return一个值。相反,尝试访问 属性 值会引发 AggregateException 异常。
唯一的区别是 await 不会阻塞。相反,它将异步等待 Task 完成,然后恢复
await
异步解包任务的结果,而仅使用 Result 会阻塞直到任务完成。
See this explanantion from Jon Skeet.
执行以下操作有什么区别:
async Task<T> method(){
var r = await dynamodb.GetItemAsync(...)
return r.Item;
}
对
async Task<T> method(){
var task = dynamodb.GetItemAsync(...)
return task.Result.Item;
}
在我的例子中,出于某种原因,只有第二个有效。第一个似乎永远不会结束。
task.Result is accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method。 一旦操作的结果可用,它就会被存储,并在随后对结果 属性 的调用中立即被 return 编辑。注意,如果任务运行过程中发生异常,或者任务被取消,Result属性不会return一个值。相反,尝试访问 属性 值会引发 AggregateException 异常。 唯一的区别是 await 不会阻塞。相反,它将异步等待 Task 完成,然后恢复
await
异步解包任务的结果,而仅使用 Result 会阻塞直到任务完成。
See this explanantion from Jon Skeet.