Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Different ways to run this code asynchronously?

I have this code

List<string> myList = new List<string>();

myList.AddRange(new MyClass1().Load());
myList.AddRange(new MyClass2().Load());
myList.AddRange(new MyClass3().Load());

myList.DoSomethingWithValues();

What's the best way of running an arbitrary number of Load() methods asynchronously and then ensuring DoSomethingWithValues() runs when all asynchronous threads have completed (of course without incrementing a variable every time a callback happens and waiting for == 3)

like image 654
Bob Avatar asked Apr 24 '26 17:04

Bob


2 Answers

My personal favorite would be:

List<string> myList = new List<string>();

var task1 = Task.Factory.StartNew( () => new MyClass1().Load() );
var task2 = Task.Factory.StartNew( () => new MyClass2().Load() );
var task3 = Task.Factory.StartNew( () => new MyClass3().Load() );

myList.AddRange(task1.Result);
myList.AddRange(task2.Result);
myList.AddRange(task3.Result);

myList.DoSomethingWithValues();
like image 109
Reed Copsey Avatar answered Apr 27 '26 06:04

Reed Copsey


How about PLINQ?

var loadables = new ILoadable[] 
                { new MyClass1(), new MyClass2(), new MyClass3() };

var loadResults = loadables.AsParallel()
                           .SelectMany(l => l.Load());

myList.AddRange(loadResults);

myList.DoSomethingWithValues();

EDIT: Changed Select to SelectMany as pointed out by Reed Copsey.

like image 26
Ani Avatar answered Apr 27 '26 06:04

Ani