for (long key = 0; key < 5; key++)
{
var processingThread = new Thread(() => Setup(key));
processingThread.Start();
}
I want to execute the Setup(key) function with each key value but at the same time on multiple windows..
for (long key = 0; key < 5; key++)
{
var processingThread = new Thread(() => Setup(key));
processingThread.Start();
}
I want to execute the Setup(key) function with each key value but at the same time on multiple windows..
You need to capture a local copy of key within the for loop otherwise by the time the threads actually call Setup the value of key has become 5. If you capture a local copy then that value doesn't change and all works as expected.
for (long key = 0; key < 5; key++)
{
var localKey = key;
var processingThread = new Thread(() => Setup(localKey));
processingThread.Start();
}
Check out the Parallel.ForEach() and Parallel.For() methods.
https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx
Explicitly creating a new thread has large overhead and should be avoided. Only do it if have good reason and already have considered using a thread pool based solution (such as PTL, or similar).
for (long key = 0; key < 5; key++)
{
var processingThread = new Thread(Setup);
processingThread.Start(key);
}
Setup parameter type must be changed to object (and casted, if needed)
If Parallel.For() does not provide the trick you can pass them all a AutoResetEvent.
Call Wait() in all your delegates and then call Set() after creating all the threads.
Please take notice in the fact that the system does
// THIS ISN'T TESTED AND IS WRITTEN HERE, SO MIND THE SYNTAX, THIS MIGHT NOT COMPILE !!
AutoResetEvent handle = new AutoResetEvent(true);
for (long key = 0; key < 5; key++)
{
var processingThread = new Thread(() =>
{
handle.Wait();
Setup(key)
} );
processingThread.Start();
}
handle.Set();