I have a collection of modules to be initialised and 3 of the modules take a long time whereas others take very little time to initialise. Currently if do all of them on the same thread it takes a lot of time e.g.
foreach (var m in modules)
{
var md = m;
md.Initialise();
}
so I am trying something like
foreach (var m in modules)
{
Task.Factory.StartNew(()=>{
var md = m;
md.Initialise();
}, TaskCreationOptions.Longrunning);
}
Also tried:
Parallel.ForEach(modules, m => m.Initialize());
Neither of these works because it won't wait for all modules to be initialised. I need all modules to be initialised before the UI thread can continue otherwise the UI will start up very quickly after the first module initialised and UI becomes an empty shell due to other modules still uninitialized. Is there any way to achieve each module initialised on separate thread and the main thread will wait until they are ALL initialised? Hope I have made myself clear. Thanks.
You can do your foreach
in parallel:
Parallel.ForEach(modules, m => m.Initialize());