Mbt*_*925 2 c# multithreading c#-3.0
我有一个主线程,使两个嵌套的其他线程.
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() });
}
Run Code Online (Sandbox Code Playgroud)
每个线程将其输入参数添加到Listbox.我很困惑为什么一些线程的输入参数不在for bounds中?

你的循环正常运行,但所发生的事情是这样的:委托知道它必须通过w与h到otherthreads()功能,但这些值不绑定,直到它实际上是调用.换句话说,在委托实际执行之前,它只知道它必须使用w和h.在最后一次迭代中,您要求委托执行,但在它可以之前,w并h在初始化线程的最后时间递增,导致它们的值分别为8和6.循环退出.然后,picomoments后来,委托执行,NOW的值为w和h......但是值现在是8和6.
您可以通过"快照" w和h局部变量来避免这种情况,以及代理周围最紧密的范围并适当地分配它们的值:
for (int h = 0; h < 5; h+=3)
{
int h2=h;
int w2=w;
Thread t = new Thread(delegate() { otherthreads(w2, h2); });
ts.Add(t);
t.Start();
}
Run Code Online (Sandbox Code Playgroud)