简体   繁体   中英

Executing parallel tasks -> wait for all -> make use of result

GetSystems() and GetActions() both returns IEnumerable<T> of different types. What do I need to do to access the results below? Do I need to make use of Task.WaitAll() or something similar?

Task t1 = new Task(() => GetSystems());
Task t2 = new Task(() => GetActions());

List<Task> tasks = new List<Task>() { t1, t2 };

Parallel.ForEach(tasks, t =>
                          {
                              t.Start();
                          });

//t1.Result...?

I'm using C# 4.0.

Update:

private Task<List<SYSTEM>> GetSystems()
{
    return Task.Factory.StartNew(() =>
    {
        using (var context = new DbContext())
        {
            return context.SYSTEM.ToList();
        }
    });
}

You need to use Task<T> in order to use the Result property. Given the comments, it looks like you want:

Task<List<SYSTEM>> t1 = ...;
Task<List<ACTION>> t2 = ...;

Task[] tasks = { t1, t2 };

Parallel.ForEach(tasks, t => t.Start());

Task.WaitAll(tasks);

List<SYSTEM> systems = t1.Result;
List<ACTION> actions = t2.Result;

You should consider how you'll handle failure cases though.

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