C#线程数组
C# thread array
我对 C# 中的线程数组有疑问。当我启动线程 if for 循环并发送参数时,一些线程获得相同的值。
Thread[] nit = new Thread[n];
for (int i = 0; i < n; i++)
{
nit[i] = new Thread(() => functionThread(i + 1)); //functionThread => thread
nit[i].IsBackground = true;
nit[i].Name = string.Format("Thread: {0}", i + 1);
nit[i].Start();
Thread.Sleep(500); //I have problem here
}
for (int i = 0; i < n; i++)
{
nit[i].Join();
}
如果 n = 4,线程中的值应为 1、2、3、4。但是如果我删除 "Thread.Sleep(500);" 或我将值设置为小于 500,则值变为例如 2、2、3, 4.
我如何在没有 Thread.Sleep() 的情况下完成这项工作并且在线程中仍然具有正确的值?
提前致谢。
试试这个:
int iLocal = i;
nit[i] = new Thread(() => functionThread(iLocal + 1)); //functionThread => thread
发生这种情况是因为您传递的是变量,而不是值。这是类似的问题:Captured variable in a loop in C#
您可以从 Jon 的 post 那里了解更多关于闭包的信息:http://csharpindepth.com/Articles/Chapter5/Closures.aspx
我对 C# 中的线程数组有疑问。当我启动线程 if for 循环并发送参数时,一些线程获得相同的值。
Thread[] nit = new Thread[n];
for (int i = 0; i < n; i++)
{
nit[i] = new Thread(() => functionThread(i + 1)); //functionThread => thread
nit[i].IsBackground = true;
nit[i].Name = string.Format("Thread: {0}", i + 1);
nit[i].Start();
Thread.Sleep(500); //I have problem here
}
for (int i = 0; i < n; i++)
{
nit[i].Join();
}
如果 n = 4,线程中的值应为 1、2、3、4。但是如果我删除 "Thread.Sleep(500);" 或我将值设置为小于 500,则值变为例如 2、2、3, 4.
我如何在没有 Thread.Sleep() 的情况下完成这项工作并且在线程中仍然具有正确的值?
提前致谢。
试试这个:
int iLocal = i;
nit[i] = new Thread(() => functionThread(iLocal + 1)); //functionThread => thread
发生这种情况是因为您传递的是变量,而不是值。这是类似的问题:Captured variable in a loop in C#
您可以从 Jon 的 post 那里了解更多关于闭包的信息:http://csharpindepth.com/Articles/Chapter5/Closures.aspx