C#线程中的闭包和捕获变量

时间:2018-06-02 01:25:11

标签: c# thread-safety

考虑代码:

using System;
using System.Threading;

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

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

实际输出是:

=== Test 0
=== Test 6
=== Test 3
=== Test 5
=== Test 8
=== Test 9
=== Test 2
=== Test 4
=== Test 7
=== Test 1

我的例外输出应如下所示:

=== Test 0
=== Test 1
=== Test 2
=== Test 3
=== Test 4
=== Test 5
=== Test 6
=== Test 7
=== Test 8
=== Test 9

正如您在上面看到的那样,输出超出了我的预期;我应该修改代码以使其运行,因为我除外?我很困惑......

0 个答案:

没有答案