2012-10-19 2 views
1

나는 NuGet에서 System.Json (베타)을 사용해 보았습니다. 또한, 단지 await 블록 모든 일이 완료 될 때까지 ContinueWith 경우 사용하는 경우 궁금 비주얼 스튜디오 2012Await and ContinueWith

땜질 시작,이 새로운 async/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)); 

?

답변

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

당신은 참으로 awaitTaskContinueWith에 의해 반환 ING하고 ContinueWith 계속이 완료 될 때까지 json 변수에 할당이 발생하지 않습니다 :

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

일반적으로 s 피킹, 나는 ContinueWith 코드를 쓸 때 async 코드를 피한다. 아무것도 과 함께이 아니지만 약간 낮은 수준이며 구문이 더 어색합니다. '이 데이터 액세스 계층의 일부 경우

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

가 나는 또한 ConfigureAwait(false)을 사용하지만 response.Content에 접근하고 있기 때문에 직접 당신 가정 : 귀하의 경우

, 나는 같은 것을 할 것 나중에이 메서드에서 ASP.NET 컨텍스트가 필요합니다.

async/await을 처음 사용 하셨기 때문에 내 async/await intro이 도움이 될 수 있습니다.

관련 문제