I have a main thread that makes some other threads in two nested for.
private void mainthread()
{
List<Thread> ts= new List<Thread>();
for (int w=0; w<7; w+=2)
for (int h = 0; h < 5; h+=3)
{
Thread t = new Thread(delegate() { otherthreads(w, h); });
ts.Add(t);
t.Start();
}
for (int i = 0; i < ts.Count; i++)
ts[i].Join();
}
private void otherthreads(int w, int h)
{
listBox1.Invoke(new singleparam(addtolistbox), new object[] { "w:" + w.ToString() + ",h:" + h.ToString() });
}
Each thread adds it’s input arguments to a Listbox. I am confused why the input arguments of some threads are not in the for bounds?

Your loop is running correctly, but what is happening is this: the delegate knows that it must pass
wandhonto theotherthreads()function, but those values are not bound until it is actually invoked. In other words, prior to the delegate actually executing, it just knows it must usewandh. On your last iteration, you are asking for the delegate to execute, but before it can,wandhincrement for the final time on the initiating thread, causing their values to be 8 and 6, respectively. The loops exit. Then, picomoments later, the delegate executes and NOW has the values ofwandh… but the values are now 8 and 6.You can avoid this by “snapshotting”
wandhwith local variables to the tightest scope around the delegate and assigning their values appropriately: