|
|
| | |
thread[i].Join() question Posted: 08 Mar 07 8:29 PM (N/A) |
| | |
I have a question coming from the book. It has to do with the placement of the .Join() method. Below is code similar to the book (currently commented out) and something I would have done. They work identical (as far as I can tell, but hey, it's late at night). What is the difference between putting the .Join() in the same loop as you do the .Start() or in another loop outside?
using System; using System.Collections.Generic; using System.Text; using System.Threading;
namespace JoiningTest { class Program { public static Random random = new Random();
static void Main(string[] args) { Thread[] threads = new Thread[5];
for (int i = 0; i < threads.Length; i++) { ParameterizedThreadStart operation = new ParameterizedThreadStart(DoWork); threads[i] = new Thread(operation); threads[i].Start(threads[i].ManagedThreadId); threads[i].Join(); }
//for (int i = 0; i < threads.Length; i++) //{ // Console.WriteLine("Waiting to join"); // threads[i].Join(); // Console.WriteLine("back from waiting."); //} Console.WriteLine("Am I done yet?"); }
public static void DoWork(Object ThreadId) { for (int i = 0; i < 10; i++) { int sleepTime = random.Next(1000); Console.WriteLine((int)ThreadId + ")\t" + i + "\tsleeping for:" + sleepTime); Thread.Sleep(sleepTime); } } } }
|
| |
| | |
Re: thread[i].Join() question Posted: 05 Jul 07 8:36 AM (N/A) |
| | |
Hi Flip,
When the .join is called, the calling thread (the one executing the loop) is put in a blocked state until the thread that it joined is completed.
So in your case the next thread, in the interation, will not be started until the previous one has completed.
If you placed the .join call outside of the loop, then all of the threads will get a chance to start. Now depending on which thread you called your .join on, the calling thread would blocked until its done.
|
| |
| | |
Re: thread[i].Join() question Posted: 05 Jul 07 8:42 AM (N/A) |
| | |
| |
| | .NET Development MCTS 70-536 Study Group thread[i].Join() question | | |
| | | |