user584018 user584018 - 2 months ago 23
C# Question

How to aggregate multiple task results

I created 2 Tasks in below code snipet, now I would like to club both tasks results into a single variable:

public class DataPoint
{
public int Id { get; set; }
public string Data { get; set; }
}

public class Worker
{
public void DoProcessing()
{
List<DataPoint> dp = new List<DataPoint>();

Task task1 = Task.Factory.StartNew(() => Process1(dp));
Task task2 = Task.Factory.StartNew(() => Process2(dp));

Task.WhenAll(task1, task2);

//var finalResult = task1 result + Task 2 results
}

private List<DataPoint> Process1(List<DataPoint> dp1)
{
return dp1;
}
private List<DataPoint> Process2(List<DataPoint> dp2)
{
return dp2;
}
}

Answer

If you want to join those two lists, you'll first need to mark your method as async Task, and then await Task.WhenAll in order to asynchronously wait for both tasks to complete:

public async Task DoProcessingAsync()
{
    var task1 = Task.Run(Process1);
    var task2 = Task.Run(Process2);

    var result = await Task.WhenAll(task1, task2);
    var finalResult = task1.Result.Concat(task2.Result).ToList();
}

private List<DataPoint> Process1()
{
    return new List<DataPoint>();
}

private List<DataPoint> Process2()
{
    return new List<DataPoint>();
}

If you're using .NET 4.5 or above, prefer Task.Run over Task.Factory.StartNew.

Also, List<T> isn't thread safe, don't pass a list to be returned by the ProcessX method inside your task. Make each return a fresh List<DataPoint> so you won't have threading issues.