I have one 'main' server, and several other servers (Extensions) which need to be controlled by the main server.
The Extensions each have a Web Reference to their respective server. Controlling these extensions is done by Init(), Start() and Stop() web calls. Up until now I did this synchronously, the main server for example calls:
public void InitExtensions()
{
foreach (Extension extension in GetEnabledExtensionList())
{
extension.Init();
}
}
And than:
public void StartExtensions()
{
foreach (Extension extension in GetEnabledExtensionList())
{
extension.Start();
}
}
Where the extension.Init() and extension.Start() will do the webcalls.
Now I want to do this asynchronously, but the tricky part is that the StartExtensions() method should wait for the extension.Init() to be finished. A different Extension can of course be started before another one is initialized.
What is the best way to do this? I think I will need for example lists
List<Thread> _InitThreads;
List<Thread> _StartThreads;
List<Thread> _StopThreads;
And check if each list contains a thread for the respective Extension, and Join() it to wait execution. This gets however very difficult very fast...
You can use parallel foreach. This executes the iterations in parallel(asynchronously) and waits until all iterations are finished(means next call after foreach will be executed after all iterations have finished working)
Parallel.ForEach(GetEnabledExtensionList(), (extension) =>
{
extension.Init();
extension.Start();
});
This is a good way because you will know, when all of your servers have been started and also the parallel Tasks/Threads will be handled efficiently(number, priority, etc.) by the OS.