2

我有一个主线程,它使两个嵌套的其他线程成为。

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() });        
        }

每个线程将其输入参数添加到列表框。我很困惑为什么某些线程的输入参数不在 for 范围内?

在此处输入图像描述

4

1 回答 1

5

您的循环运行正常,但发生的情况是:委托知道它必须传递w并传递hotherthreads()函数,但这些在实际调用之前不会绑定。换句话说,在委托实际执行之前,它只知道它必须使用wand h。在您的最后一次迭代中,您要求委托在执行之前执行,wh在启动线程的最后一次递增,导致它们的值分别为 8 和 6。循环退出。然后,picomoments 之后,代理执行并且现在具有wh...的值,但现在的值是 8 和 6。

您可以通过“快照”wh局部变量在委托周围最紧密的范围内并适当地分配它们的值来避免这种情况:

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();
}
于 2012-07-16T16:45:30.643 回答