How to get the return value of tasks when using Task.WaitAll ()

I need to get the return value of several Task<List<string>>executed in parallel and merge them into a new one List<string>.

This is what I have now. As you can see in the violin, tasks are executed in parallel (execution time is about 1 s). The problem is not how to get the return value (a List<string>object) from each execution so that I can combine them.

Fiddle: https://dotnetfiddle.net/91YqkY

code:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var filters = new List<string>
        {
            "A", "B", "C"
        }

        ;
        var api = new API();
        var TaskList = new List<Task>();
        foreach (var f in filters)
        {
            var LastTask = new Task<List<String>>(() =>
            {
                return api.GetArray(f);
            }

            );
            LastTask.Start();
            TaskList.Add(LastTask);
        }

        Task.WaitAll(TaskList.ToArray());
        foreach (var t in TaskList)
        {
            // I need to get the List<string> returned in each GetArray and merge them
        }
    }
}

public class API
{
    public List<string> GetArray(string param)
    {
        Thread.Sleep(1000);
        return new List<String>{
            param + "1",
            param + "2",
            param + "3",
        };
    }
}
+4
source share
1 answer

You can try using the method SelectMany:

var result = TaskList.Select(t => t.Result)
                     .SelectMany(r => r)
                     .ToList();

TaskList, TaskList<string>, , List<string>, SelectMany . , : ToList, , List<string>.

, TaskList.

var TaskList = new List<Task<List<string>>();
+5

Source: https://habr.com/ru/post/1624336/


All Articles