簡體   English   中英

多線程行為奇怪的C#!

[英]multithreading behavior strange 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循環而言未修復。)

關閉。 您必須在線程中復制大量變量以使其保持當前值。

現在,所有線程都將讀取它們運行時具有的任何值的變量i-而不是為其調用thread.start時具有的值。

在for循環內創建Thread對象時,不會調用testThread每當計划線程運行時,都會調用該方法。 那可能會在以后發生。

在您的情況下,線程在for循環結束后開始運行-那時i等於3。因此testThread被調用3次,值3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM