Is this a bad way to multithread?
-
Thread[] workerThread = new Thread[someInt]; for(int i = 0; i < someInt; i++) { string keyInfo = someKeyInfo().ToString(); workerThread[i] = new Thread(new ThreadStart(DoSomeWork(keyInfo))); workerThread[i].Start(); } foreach(Thread t in workerThread) { while(t.IsAlive()){} }
-
Thread[] workerThread = new Thread[someInt]; for(int i = 0; i < someInt; i++) { string keyInfo = someKeyInfo().ToString(); workerThread[i] = new Thread(new ThreadStart(DoSomeWork(keyInfo))); workerThread[i].Start(); } foreach(Thread t in workerThread) { while(t.IsAlive()){} }
-
Thread[] workerThread = new Thread[someInt]; for(int i = 0; i < someInt; i++) { string keyInfo = someKeyInfo().ToString(); workerThread[i] = new Thread(new ThreadStart(DoSomeWork(keyInfo))); workerThread[i].Start(); } foreach(Thread t in workerThread) { while(t.IsAlive()){} }
Depending on the number of threads you could consider using ThreadPool. Also you should rethink the IsAlive loop. First of all it could consume much processor time so you should at least do:
foreach(Thread t in workerThread)
while(t.IsAlive())
Thread.Sleep(10);Instead of waiting for all threads separately you could also use a counter which counts the started and terminated threads. Have a look at the Interlocked[^] class for a sample.
-
I didn't think called methods could have parameters in Framework 1.1. The methods used by ThreadStart must be static.
First point is correct but .Net 2.0 has a new overload for the Thread constructor accepting a ParametrizedThreadStart. Second point isn't true even under 1.1 also 'normal' functions can be used.
-
Thread[] workerThread = new Thread[someInt]; for(int i = 0; i < someInt; i++) { string keyInfo = someKeyInfo().ToString(); workerThread[i] = new Thread(new ThreadStart(DoSomeWork(keyInfo))); workerThread[i].Start(); } foreach(Thread t in workerThread) { while(t.IsAlive()){} }
-
Thread[] workerThread = new Thread[someInt]; for(int i = 0; i < someInt; i++) { string keyInfo = someKeyInfo().ToString(); workerThread[i] = new Thread(new ThreadStart(DoSomeWork(keyInfo))); workerThread[i].Start(); } foreach(Thread t in workerThread) { while(t.IsAlive()){} }
If you are going to do something like that use:
foreach(Thread t in workerThread)
{
thread.Join();
}I'd only do something like that in a simple console application and I didn't care about the results of the DoSomeWork method. Otherwise I'd use asyncronous delegates and callback methods.
I can imagine the sinking feeling one would have after ordering my book, only to find a laughably ridiculous theory with demented logic once the book arrives - Mark McCutcheon