在for循环中创建新线程并传递参数

时间:2015-08-20 20:17:09

标签: c# multithreading parallel-processing

考虑以下代码:

for(int i = 0; i < 10; i ++)
{
    new Thread(() => Test(i)).Start();
}

Test(int i)功能:

public void Test(int i)
{
    Console.WriteLine("=== Test " + i);
}

实际输出:

  

===测试3
  ===测试4
  ===测试4
  ===测试5
  ===测试5
  ===测试5
  ===测试9
  ===测试9
  ===测试9
  ===测试10

你可以看到一些数字丢失而其他一些数字被重复。

预期输出:

我希望以随机顺序看到所有数字。

问题

我应该锁定任何变量/方法吗?我该如何解决这个问题?

3 个答案:

答案 0 :(得分:5)

  

我应该锁定任何变量/方法吗?我该如何解决这个问题?

您的问题是关闭捕获的变量

将您的代码更改为

for(int i = 0; i < 10; i ++)
{
    int tmp = i;
    new Thread(() => Test(tmp)).Start();
}

了解更多信息:http://csharpindepth.com/articles/chapter5/closures.aspxhttp://geekswithblogs.net/rajeevr/archive/2012/02/26/closures-and-captured-variable.aspx

答案 1 :(得分:3)

overload of the Thread.Start method个参数。使用它,你可以避免关闭:

for(int i = 0; i < 10; i ++)
{
    new Thread(o => Test((int)o)).Start(i);
}

答案 2 :(得分:1)

更新(适用于.net 4.0以后): 您可以编写一个Parallel.For循环而不是for循环,它将真正利用并行处理。

  Parallel.For(0, 10, i =>
            {
                new Thread(() => Test(i)).Start();
            });