在for循环中创建新线程并传递参数
Create new threads in a for loop and pass parameters
考虑这段代码:
for(int i = 0; i < 10; i ++)
{
new Thread(() => Test(i)).Start();
}
Test(int i)
函数:
public void Test(int i)
{
Console.WriteLine("=== Test " + i);
}
实际输出:
=== Test 3
=== Test 4
=== Test 4
=== Test 5
=== Test 5
=== Test 5
=== Test 9
=== Test 9
=== Test 9
=== Test 10
如您所见,有些号码丢失了,有些号码重复了。
预期输出:
我希望看到所有数字都是随机排列的。
问题
我应该锁定任何 variables/methods 吗?我该如何解决这个问题?
Should I lock any variables/methods? How can I fix this?
您的问题在于 Closure 和 Captured Variables
将代码更改为
for(int i = 0; i < 10; i ++)
{
int tmp = i;
new Thread(() => Test(tmp)).Start();
}
欲了解更多信息:http://csharpindepth.com/articles/chapter5/closures.aspx 或
http://geekswithblogs.net/rajeevr/archive/2012/02/26/closures-and-captured-variable.aspx
有一个带有参数的 overload of the Thread.Start method。使用它,您可以避免关闭:
for(int i = 0; i < 10; i ++)
{
new Thread(o => Test((int)o)).Start(i);
}
更新(.net 4.0 以上):
您可以编写一个真正利用并行处理的 Parallel.For 循环,而不是 for
循环。
Parallel.For(0, 10, i =>
{
new Thread(() => Test(i)).Start();
});
考虑这段代码:
for(int i = 0; i < 10; i ++)
{
new Thread(() => Test(i)).Start();
}
Test(int i)
函数:
public void Test(int i)
{
Console.WriteLine("=== Test " + i);
}
实际输出:
=== Test 3
=== Test 4
=== Test 4
=== Test 5
=== Test 5
=== Test 5
=== Test 9
=== Test 9
=== Test 9
=== Test 10
如您所见,有些号码丢失了,有些号码重复了。
预期输出:
我希望看到所有数字都是随机排列的。
问题
我应该锁定任何 variables/methods 吗?我该如何解决这个问题?
Should I lock any variables/methods? How can I fix this?
您的问题在于 Closure 和 Captured Variables
将代码更改为
for(int i = 0; i < 10; i ++)
{
int tmp = i;
new Thread(() => Test(tmp)).Start();
}
欲了解更多信息:http://csharpindepth.com/articles/chapter5/closures.aspx 或 http://geekswithblogs.net/rajeevr/archive/2012/02/26/closures-and-captured-variable.aspx
有一个带有参数的 overload of the Thread.Start method。使用它,您可以避免关闭:
for(int i = 0; i < 10; i ++)
{
new Thread(o => Test((int)o)).Start(i);
}
更新(.net 4.0 以上):
您可以编写一个真正利用并行处理的 Parallel.For 循环,而不是 for
循环。
Parallel.For(0, 10, i =>
{
new Thread(() => Test(i)).Start();
});