仅使用异步任务和任务有什么区别?

Gle*_*cia 8 c# parallel-processing asynchronous task task-parallel-library

例如,这段代码之间的区别

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>>);
    }
Run Code Online (Sandbox Code Playgroud)

然后

 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);
    }
Run Code Online (Sandbox Code Playgroud)

哪一个正确或更快?只是调用这个方法需要等待或只是一个任务?

Ste*_*ary 6

async一个更好.你应该总是喜欢用await而不是ContinueWith.我在博客上详细介绍了为什么ContinueWith不好.

这两种实现之间的语义差异是由于两个不同:是否async使用,以及是否ContinueWith使用.

删除async更改异常语义.当async使用时,任何异常(由编译器生成的状态机)抓住和放置在返回的任务.没有async,直接(同步)引发异常.所以,如果BasePath,AppendPathSegment,SetQueryParams,或GetStringAsync抛出(或返回null或类似的东西),则该异常将被同步而不是异步上调,这可能是混乱的来电.

使用ContinueWith更改执行语义.在这种情况下,Deserialize将安排在TaskScheduler.Current.这种对电流的依赖TaskScheduler是最棘手的部分之一ContinueWith.

  • @GlebPatcia:在这种情况下你应该使用`WhenAll`而不是`WaitAll`.你总是可以使用`await`而不是`ContinueWith`.有时您只需要引入一种新方法.就像`async Task GetAndProcessAsync(...){await _newsService.GetAll(..); ContinuationAction(); 然后可以用作`await Task.WhenAll(GetAndProcessAsync(..),..);` (2认同)

Kir*_*ill 5

两种方法都返回相同的类型:Task.但async方法允许await在他的身体中使用关键字.它通知编译器生成状态机await及其全部.关于async/await性能你可以阅读这篇文章