多线程行为奇怪的C#!

马德

这是我的应用程序,以执行线程示例为例,但是输出与预期不符,任何人对此都有任何线索

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();
        }
    }
}

但是出来却是

3__

3__

3__

3__

3__

3__

3__

3__

3__

3__

4__

4__

4__

4__

4__

究竟谁能解释会发生什么,请谢谢

马修·沃森

请参阅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();
}

(请注意,对于foreach循环,此问题已在.Net 4.5中修复,但对于for循环未修复。)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章