简体   繁体   中英

calling async method in parallel c#

I have a method which takes a int input and return Task<Dictionary<DateTime, HistPrice>>

public static async Task<Dictionary<DateTime, HistPrice>> GetPrices(int seriesId) {
    ...
    return Dictionary<DateTime, HistPrice>;
}

Now I want to call the above method for list of values 1,2,3,4,5,6,7,8 in parallel.

List<int> seriesIdDist = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });

var tasks = new List<Task>();
foreach(var t in seriesIdDist) {
    tasks.Add(GetPrices(t));
}
await Task.WhenAll(tasks);

Till here everything is working fine, problem is in extracting the result from the task. I tried to extract the result like

foreach(var ta in tasks) {
    var res = await ta;//error in this line
}

but it says

CS0815 Cannot assign void to an implicitly-typed variable

What am I missing here ?

Instead of

var tasks = new List<Task>();

Use this instead:

var tasks = new List<Task<Dictionary<DateTime, HistPrice>>>();

Or replace it and your foreach loop with a little bit of LINQ, which saves you from having to worry about the type.

var tasks = seriesIdDist.Select( n => GetPrices(n) ).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM