Would there a more elegant way of writing the following syntax?
Thread t0 = new Thread(new ParameterizedThreadStart(doWork));
t0.Start('someVal');
t0.Join();
Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someDiffVal');
t1.Join();
Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?
If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:
Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someVal');
t1.Start('someDiffVal');
Why would you start a thread and then join against it immediately?
I'd normally do something like this:
List<Thread> threads = new List<Thread>();
foreach (string item in items)
{
string copy = item; // Important due to variable capture
ThreadStart ts = () => DoWork(copy); // Strongly typed :)
Thread t = new Thread(ts);
t.Start();
threads.Add(t);
}
foreach (Thread t in threads)
{
t.Join();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With