Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 676
user584018 Avatar asked Oct 23 '25 21:10

user584018


1 Answers

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.

like image 83
Yuval Itzchakov Avatar answered Oct 25 '25 11:10

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!