Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return value of tasks when using Task.WaitAll() [duplicate]

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

This is what I have currently. As you can see in the fiddle, the tasks are being executed in parallel (execute time is about 1s). Problem is don't know how to get the returned value (a List<string> object) from each execution so I can merge 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",
        };
    }
}
like image 909
empz Avatar asked Jan 14 '16 19:01

empz


1 Answers

You could try to use the SelectMany method:

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

Initially you project each element of the TaskList, which is a TaskList<string> object, to it's result which in your case is a List<string> and then using the SelectMany method you define a sequence of all the strings in the results of the tasks. Last but not least, you have to call the ToList, in order your query to be executed and to get as a result a List<string>.

Update

As Sergey correctly pointed out in his comment below, you have to redefine your TaskList.

var TaskList = new List<Task<List<string>>();
like image 196
Christos Avatar answered Nov 20 '22 21:11

Christos