views:

55

answers:

1
+5  A: 

You need to pass each new thread an entirely new object. Currently they all get a reference to the same object in the main thread, i.e. oTaskParameters

Try this, after making MyNumber settable as a param on MyThreadInfo constructor:

for (int i = 1; i <= 5; i++)
{
    MyThreadInfo oTaskParameters = new MyThreadInfo(i);
    objTaskParameters.MyGuid = Guid.NewGuid();
    ThreadPool.QueueUserWorkItem(new WaitCallback(objTask.ProcessDataForNTime), objTaskParameters);
}

MyThreadInfo(int i) : MyNumber(i)
{
  // rest of construction logic
}

This change means that each new thread gets a disjoint instance of MyThreadInfo, with the id for that thread set appropriately.

There is still no guarantee that the threads will print out their ids in ascending order. You'd have to introduce some type of FIFO queue/processing to enforce that. There is a detailed discussion of that issue ordering of thread execution using Threadpool.QueueUserWorkItem.

Steve Townsend
Perfect. I'm not so worried about order, just being able to identify the threads as they happen. Thanks for your help!
Sam
@Sam - glad this helped
Steve Townsend