【问题标题】:multithreading behavior strange C#!多线程行为奇怪的 C#!
【发布时间】:2015-01-07 19:08:57
【问题描述】:

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

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__

究竟发生了什么,任何人都可以解释一下 谢谢

【问题讨论】:

  • 预期的输出是什么,为什么会这样?
  • 预期为1__五次,2__五次,3__次五次,顺序不重要

标签: c# multithreading


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    关闭。您几乎必须在线程中复制变量才能保持当前值。

    Wight 现在所有线程都使用它们在运行时所拥有的任何值来读取变量 i,而不是使用为其调用 thread.start 时所拥有的值。

    【讨论】:

      【解决方案3】:

      testThread 在 for 循环中创建 Thread 对象时不会被调用 - 只要线程计划运行,就会调用该方法。这可能会在以后发生。

      在您的情况下,线程在 for 循环结束后开始运行 - 到那时,i 等于 3。因此,testThread 被调用了 3 次,值为 3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 2018-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多