将LINQ与异步混合(从种子中获取有效负载)

时间:2016-11-03 16:00:58

标签: c# .net linq async-await system.reactive

我有种子集合

var seeds = new [] {1, 2, 3, 4};

从每个种子我想运行一个异步方法,用种子执行一些计算:

async Task<int> Calculation(int seed);

我的目标是执行这样的选择:

var results = from seed in seeds
              let calculation = await Calculation(seed)
              select new { seed, calculation };

不幸的是,使用LINQ不允许使用此语法。

如何让“results”变量同时包含种子和计算?

(我很感激任何答案,但特别是如果它使用System.Reactive的Observable

3 个答案:

答案 0 :(得分:3)

这是一个Rx解决方案:

var seeds = new [] {1, 2, 3, 4};
var results = Observable.ToObservable(seeds)
    .SelectMany(async i => new { seed = i, calculation = await Calculation(i)})
    .ToEnumerable();

答案 1 :(得分:2)

您可以使用WhenAll静态方法执行以下操作:

var r= await Task.WhenAll(seeds.Select(async seed =>new {
                                                          Seed= seed,
                                                          Result = await Calculation(seed) 
                                                        }
                                      )
                         );  

答案 2 :(得分:1)

更改您的异步功能,以返回计算出的数字和给定的var Calendar: JCalendar; UsedFirstDayOfWeek: integer; begin //For default locale use code Calendar := TJCalendar.JavaClass.getInstance(TJLocale.JavaClass.getDefault); //For US locale (etc UK, ...) use code Calendar := TJCalendar.JavaClass.getInstance(TJLocale.JavaClass.US); UsedFirstDayOfWeek:= Calendar.getFirstDayOfWeek; //Constants used in result SUNDAY Constant Value: 1 (0x00000001) MONDAY Constant Value: 2 (0x00000002) TUESDAY Constant Value: 3 (0x00000003) WEDNESDAY Constant Value: 4 (0x00000004) THURSDAY Constant Value: 5 (0x00000005) FRIDAY Constant Value: 6 (0x00000006) SATURDAY Constant Value: 7 (0x00000007) end;

seed

然后使用linq返回public static async Task<Output> Calculation(int seed) { return new Output { Seed = seed, Result = 0 }; } public class Output { public int Seed { get; set; } public int Result { get; set; } } Task[]WaitAllWaitAll vs WhenAll

WhenAll