Multithreaded behavior weird C #!

this is my application to exclude streaming example, but the output is not as expected, does anyone know about this, 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 out but

3 __

3 __

3 __

3 __

3 __

3 __

3 __

3 __

3 __

3 __

4 __

4 __

4 __

4 __

4 __

what is happening can anyone explain please thanks

+4
source share
3 answers

See Eric Lippert for an excellent blog entry on this issue.

This is caused by access to the "modified closure" .

Change the loop body as follows:

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 the loop foreachthis was fixed in .Net 4.5, but it was not fixed for the loop for.)

+11
source

. , .

Wight , - , thread.start.

+3

testThreadit is not called when creating objects Threadin a for loop - the method is called whenever a thread starts. And this may happen later.

In your case, the threads started working after the for loop ended - by then it iwas 3. Thus, it testThreadis called 3 times with a value 3.

0
source

All Articles