1

System.JsonNuGetから(ベータ版)を試していました。asyncまた、この新しいものを理解しようとして、awaitVisualStudio2012でいじくり回し始めました。

すべてが完了するまでブロックを使用するContinueWithかどうか疑問に思いますか?await

例:これは:

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

4

1 に答える 1

3

それらは似ていますが同一ではありません。

ContinueWithTask継続を表すを返します。だから、あなたの例を取るために:

JsonValue json = await response.Content.ReadAsStringAsync()
    .ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));

次の式だけを考えてみましょう。

                       response.Content.ReadAsStringAsync()
    .ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));

この式の結果は、Taskによってスケジュールされた継続を表しContinueWithます。

だから、あなたがawaitその表現をするとき:

                 await response.Content.ReadAsStringAsync()
    .ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));

あなたは確かにによって返されたものを使用しており、変数への割り当ては継続が完了awaitするまで行われません。TaskContinueWithjsonContinueWith

JsonValue json = await response.Content.ReadAsStringAsync()
    .ContinueWith<JsonValue>(respTask => JsonValue.Parse(respTask.Result));

一般的に言って、私はコードContinueWithを書くときは避けasyncます。何も問題はありませんが、少し低レベルであり、構文はより厄介です。

あなたの場合、私はこのようなことをします:

var responseValue = await response.Content.ReadAsStringAsync();
var json = JsonValue.Parse(responseValue);

ConfigureAwait(false)これがデータアクセス層の一部である場合にも使用しますが、response.Content直接アクセスしているため、このメソッドの後半でASP.NETコンテキストが必要になると思います。

async/は初めてなのでawait、私のasync/awaitイントロが役立つかもしれません。

于 2012-10-19T18:23:21.863 に答える