c# - 多线程行为奇怪的 C#!

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

但出来却是

3__

3__

3__

3__

3__

3__

3__

3__

3__

3__

4__

4__

4__

4__

4__

到底发生了什么任何人都可以解释 谢谢

最佳答案

See Eric Lippert's excellent blog post on this issue.

这是由访问 "modified closure" 引起的.

将循环的主体更改为:

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 循环则未修复。)

关于c# - 多线程行为奇怪的 C#!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861437/

相关文章:

c# - 如何使用非托管导出将函数指针从 C++ 发送到 C# dll 以用作回调

c# - 什么是NullReferenceException,如何解决?

python - Python 上 Qt 中的 QThread

c# - 如何使用 c#.net 4.0 在最大定义的并行线程中运行任务

multithreading - 从 channel 读取或超时?

multithreading - OpenGL中的多线程渲染

c# - 编译器错误取决于方法签名中的参数位置。使用未分配的局部变量

c# - 接口(interface)属性名称因类而异

c# - 将托管程序合并到非托管 C++ 可执行文件中

c# - lock(this) 和静态对象上的锁之间的区别