这两种方法之间有什么区别,似乎做同样的事情?即使使用异步/等待,它可以做到吗?
public Task<int> TaskMaxAsync1 ( Task<int>[] my_ints ) { return Task.WhenAll( my_ints ) .ContinueWith ( x => x.Result.Where ( i => i%2 != 0 ).Max( ) ) ; } public Task<int> TaskMaxAsync2 ( Task<int>[] my_ints ) { var numbers = Task.WhenAll( my_ints ).Result ; return Task.FromResult( numbers.Where( i => i%2 != 0 ).Max( ) ) ; }
解决方法
Differences between Result and ContinueWith
结果将同步阻塞,直到任务完成,并将在AggregateException中包装异常.
ContinueWith将注册该任务的回调,并在任务完成时调用该回调.
对于异步代码,Result和ContinueWith都应该被await替换.
Can it be done even with async/await?
好的,像这样:
public async Task<int> MaxAsync(Task<int>[] my_ints) { int[] ints = await Task.WhenAll(my_ints); return ints.Where(i => i % 2 != 0).Max(); }