多线程行为怪C#!

Maa*_*adh 5 c# multithreading

这是我的应用程序来执行线程示例,但输出不是预期的,任何人都有任何线索请

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace OTS_Performence_Test_tool
{
    class Program
    {

        static void testThread(string    xx)
        {

            int count = 0;
            while (count < 5)
            {
                Console.WriteLine(xx );
                count++;

            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello to the this test app ---");

            for (int i = 1; i<=3; i++)
            {

                    Thread thread = new Thread(() => testThread("" + i + "__"));

                thread.Start();

            }


            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是结果却是

3__

3__

3__

3__

3__

3__

3__

3__

3__

3__

4__

4__

4__

4__

4__

究竟有什么人可以解释,谢谢

Mat*_*son 12

请参阅Eric Lippert关于此问题的优秀博文.

这是由于访问"修改后的闭包"造成的.

将你的循环体改为:

for (int i = 1; i<=3; i++)
{
    int j = i;  // Prevent use of modified closure.
    Thread thread = new Thread(() => testThread("" + j + "__"));

    thread.Start();
}
Run Code Online (Sandbox Code Playgroud)

(请注意,对于foreach循环,这在.Net 4.5中已得到修复,但它并未针对for循环进行修复.)