2012-10-19 30 views
1

我嘗試System.Json(測試版)。此外,試圖瞭解這一新async/await東西,剛開始使用Visual Studio 2012等待和的NuGet ContinueWith

如果使用的是ContinueWith如果await塊,直到整個事情是完全想知道修改一下?

E.g,是這樣的:

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)); 

回答

3

這些都是相似但不完全相同。

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有幫助。