我在试用NuGet的System.Json (测试版)。此外,为了理解这个新的async/await内容,刚刚开始对Visual Studio2012进行修补。
想知道如果await阻塞直到整个事情完成,是否使用ContinueWith?
例如,是这样的:
JsonValue json = await response.Content.ReadAsStringAsync().ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));等同于:
string respTask = await response.Content.ReadAsStringAsync();
JsonValue json = await Task.Factory.StartNew<JsonValue>(() => JsonValue.Parse(respTask));发布于 2012-10-20 02:23:22
这些是相似的,但并不完全相同。
ContinueWith返回一个表示延续的Task。所以,以你的例子为例:
JsonValue json = await response.Content.ReadAsStringAsync()
.ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));考虑一下下面的表达式:
response.Content.ReadAsStringAsync()
.ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));该表达式的结果是一个表示由ContinueWith调度的延续的Task。
所以,当你await这个表达式的时候:
await response.Content.ReadAsStringAsync()
.ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));实际上,您正在对ContinueWith返回的Task执行await操作,只有在ContinueWith继续操作完成后,才会对ContinueWith变量进行赋值:
JsonValue json = await response.Content.ReadAsStringAsync()
.ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));一般来说,我在编写async代码时会避免使用ContinueWith。它没有什么问题,但它有点低级,语法也比较笨拙。
在您的情况下,我会这样做:
var responseValue = await response.Content.ReadAsStringAsync();
var json = JsonValue.Parse(responseValue);如果这是数据访问层的一部分,我也会使用ConfigureAwait(false),但是由于您是直接访问response.Content的,因此我假设您稍后在此方法中将需要ASP.NET上下文。
因为您是async / await的新手,所以我的async / await intro对您很有帮助。
https://stackoverflow.com/questions/12979409
复制相似问题