简体   繁体   English

多线程行为奇怪的C#!

[英]multithreading behavior strange C#!

this is my app to excute a threading example, but the output is not as expected , anyone have any clue about that please 这是我的应用程序,以执行线程示例为例,但是输出与预期不符,任何人对此都有任何线索

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

but the out but is 但是出来却是

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

3__ 3__

4__ 4__

4__ 4__

4__ 4__

4__ 4__

4__ 4__

what happens exactly anyone can explain please thanks 究竟发生了什么事,任何人都可以解释,谢谢

See Eric Lippert's excellent blog post on this issue. 有关此问题,请参见Eric Lippert的精彩博客文章。

This is being caused by access to a "modified closure" . 这是由于访问“修改后的闭包”引起的

Change your loop's body to this: 将循环的主体更改为此:

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

    thread.Start();
}

(Note that for a foreach loop, this was fixed in .Net 4.5, but it was NOT fixed for a for loop.) (请注意,对于foreach循环,此问题已在.Net 4.5中修复,但对于for循环而言未修复。)

Closure. 关闭。 You must pretty much copy the variable in the thread for it to keep the current value,. 您必须在线程中复制大量变量以使其保持当前值。

Wight now all threads read the variable i with whatever value they have at the moment they run - NOT with the value it had when thread.start was called for them. 现在,所有线程都将读取它们运行时具有的任何值的变量i-而不是为其调用thread.start时具有的值。

testThread is not called when you create the Thread objects within the for loop - the method is called whenever the thread is scheduled to run. 在for循环内创建Thread对象时,不会调用testThread每当计划线程运行时,都会调用该方法。 And that might happen later. 那可能会在以后发生。

In your case, the threads started running after the for loop ended - by that time, i was equal to 3. So testThread was invoked 3 times with the value 3 . 在您的情况下,线程在for循环结束后开始运行-那时i等于3。因此testThread被调用3次,值3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM