8

이 코드asynс 작업과 Task 만 사용하는 것의 차이점은 무엇입니까? 예를 들어

public Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h") 
    { 
     var result = _conf.BasePath 
      .AppendPathSegment("news-sentiment-indexes") 
      .SetQueryParams(new 
      { 
       from = from.ToString("s"), 
       to = to.ToString("s"), 
       grouping 
      }); 

     return result 
      .GetStringAsync() 
      .ContinueWith(Desereialize<IList<NewsSentimentIndexes>>); 
    } 

하나가 올바른지 또는 빠르게 작동하는지

public async Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h") 
    { 
     var result = _conf.BasePath 
      .AppendPathSegment("news-sentiment-indexes") 
      .SetQueryParams(new 
      { 
       from = from.ToString("s"), 
       to = to.ToString("s"), 
       grouping 
      }); 

     var newsStr = await result.GetStringAsync(); 
     return JsonConvert.DeserializeObject<NewsSentimentIndexes>(newsStr); 
    } 

차이? 그냥이 메서드를 호출하거나 기다릴 필요가 있을까요?

답변

6

async 중 하나가 더 좋습니다. 항상 ContinueWith 대신 await을 사용하는 것이 좋습니다. 내 블로그에있는 why ContinueWith is bad의 세부 정보로 이동합니다.

두 구현 간의 의미상의 차이점은 async이 사용되는지 여부와 ContinueWith이 사용되는지 여부의 두 가지 차이 때문입니다.

async을 제거하면 예외 의미가 변경됩니다. async을 사용하면 컴파일러에서 생성 한 상태 시스템에서 예외를 발견하여 반환 된 작업에 배치합니다. async이 없으면 예외가 직접 (동 기적으로) 발생합니다. 따라서 BasePath, AppendPathSegment, SetQueryParams 또는 GetStringAsync이 throw (또는 그와 같은 것을 반환)하는 경우 비동기가 아닌 동 기적으로 예외가 발생하여 호출자에게 혼란을 줄 수 있습니다.

ContinueWith을 사용하면 실행 의미가 변경됩니다. 이 경우 DeserializeTaskScheduler.Current에 예약됩니다. 현재 TaskScheduler에 대한 의존성은 ContinueWith의 가장 까다로운 부분 중 하나입니다.

+0

WaitAll과 계속되는 법을 알려주십시오. DateTime.Now) .ContinueWith (ContinuationAction), _tradingPairService.GetAllExchangeTradingPairAsync (ExchangeId, TradingPairId : 그것은 await를 –

+0

'Task.WaitAll ( _newsService.GetAll (DateTime.Now.AddYears (-1)에를 사용하는 것이 불가능하다) .ContinueWith (ContinuationAction), _companyTypesService.GetAll(). ContinueWith (ContinuationAction)); ' –

+0

나는 당신의 블로그를 읽어 주셔서 감사합니다. 그러나 동일한 작업으로 WaitAll 예제가 필요합니다. 동일의 계속과 함께 –

-3

비동기 작업은 개체를 반환하지만 작업은 수행하지 않습니다.

그래서 당신은 비동기 작업으로이 작업을 수행 할 수 있습니다

var yourTask = AsyncTask() 

를 정상적인 작업이 할 수있는 동안 :

NormalTask().someFunction() 
5

두 가지 방법 모두 동일한 유형을 반환 Task. 그러나 async 방법은 그의 시체에 await 키워드를 사용할 수 있습니다. await 및 그 모두에 대한 상태 시스템을 생성하도록 컴파일러에 알립니다. 비동기/성능에 대한 정보는 this post

+0

그러나 두 방법 모두 비동기입니다. 맞습니까? –

+0

예, 그렇습니다. 게다가'await'를 어떤 메소드 (async와 async가 아닌)와 함께 사용할 수 있습니다. – g4s8

관련 문제