I have 2 long running methods that get data from external sources and return the results as lists:
public static class Helper1
{
public static List<X> GetStuff()
{
// some long running stuff
}
}
public static class Helper2
{
public static List<Y> GetStuff()
{
// some long running stuff
}
}
I would like to run them in parallel rather than sequentially. My first attempt is:
var task1 = new Task>(() => Helper1.GetStuff()); var task2 = new Task>(() => Helper2.GetStuff());
var whenAllTask = Task.WhenAll(task1, task2);
task1.Start();
task2.Start();
Nothing seems to happen and I wonder how I can access the content of the lists afterwards (program continues sequentially). Thanks!
PS:
I am now using the following code, given Robin B's answer:
var task1 = new Task<List<X>>(() => Helper1.GetStuff(), TaskCreationOptions.LongRunning);
var task2 = new Task<List<Y>>(() => Helper1.GetStuff(), TaskCreationOptions.LongRunning);
var whenAllTask = Task.WhenAll(task1, task2).Wait();
List<X> lst1 = task1.Result;
List<Y> lst2 = task2.Result;
Unfortunately, nothing happens, It appears to be stuck.
PPS:
This seems to work for me:
var task1 = Task.Factory.StartNew<List<X>>(() => Helper1.GetStuff(), TaskCreationOptions.LongRunning));
var task2 = Task.Factory.StartNew<List<Y>>(() => Helper2.GetStuff(), TaskCreationOptions.LongRunning);
var allTasks = new Task[] { task1, task2 };
Task.WaitAll(allTasks);
List<X> lst1 = task1.Result;
List<Y> lst2 = task2.Result;
>(() => Helper1.GetStuff(), TaskCreationOptions.LongRunning);`
– Feb 11 '20 at 14:10>(() => Helper1.GetStuff());` - shouldn't this be `Helper2`?
– Rufus L Feb 11 '20 at 20:56