這些都是相似但不完全相同。
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));
你確實是await
ING通過ContinueWith
返回Task
,並且直到ContinueWith
延續已完成分配到json
變量不會發生:
JsonValue json = await response.Content.ReadAsStringAsync()
.ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));
通常s在編寫async
代碼時,我避免了ContinueWith
。沒有什麼錯誤與它,但它有點低層次,語法更尷尬。
在你的情況,我會做這樣的事情:
var responseValue = await response.Content.ReadAsStringAsync();
var json = JsonValue.Parse(responseValue);
我也將使用ConfigureAwait(false)
如果這是一個數據訪問層的一部分,但因爲你是訪問response.Content
直接我假設你」稍後在此方法中需要ASP.NET上下文。
由於您是async
/await
的新手,因此您可能會發現我的async
/await
intro有幫助。