简体   繁体   中英

C# Threading; Different results from IDE when Ran

I am trying to better my understand of threading in C# 5. I have the following code which gives me different results if I press F5 (a and b appear to get to 10) or I press CTRL F5 (a and b get to 3, as per the text in the book I am studying)... can someone please explain why? Also, I don't understand why this stops at 10 for each thread as it doesn't seem to have any sort of limit on it. Is it possible someone can explain this to me?

using System;
using System.Threading;

namespace _70483.Chapter1
{
    public static class Program
    {
        public static ThreadLocal<int> _field =
            new ThreadLocal<int>(() =>
            {
                return Thread.CurrentThread.ManagedThreadId;
            });

        public static void Main()
        {
            new Thread(() =>
            {
                for (int x = 0; x < _field.Value; x++)
                {
                    Console.WriteLine("Thread A: {0}", x);
                }
            }).Start();

            new Thread(() =>
            {
                for (int x = 0; x < _field.Value; x++)
                {
                    Console.WriteLine("Thread B: {0}", x);
                }
            }).Start();
            Console.ReadKey();
        }
    }
}

Well on my machine in debug B get to 10 and A to 9. In release without the debugger it is 2 and 3.

Nothing magic here. You are using thread local data which uses the ManagedThreadId which is just a number identifying the thread.

In debug you can see plenty threads for the application:

Not Flagged     14280   0   Worker Thread   <No Name>       Highest
Not Flagged     6180    3   Worker Thread   <No Name>       Normal
Not Flagged     4364    0   Worker Thread   <No Name>       Normal
Not Flagged     5484    7   Worker Thread   vshost.RunParkingWindow [Managed to Native Transition]  Normal
Not Flagged     4040    8   Worker Thread   .NET SystemEvents   [Managed to Native Transition]  Normal
Not Flagged     6688    9   Main Thread Main Thread MT.Program.Main Normal
Not Flagged >   13472   10  Worker Thread   <No Name>   MT.Program..cctor.AnonymousMethod__4    Normal
Not Flagged     12240   11  Worker Thread   <No Name>   MT.Program.Main.AnonymousMethod__1  Normal

In release the vshosting process is not attached and some of the other threads are not present there too, therefore you get a much smaller thread id but you should never get A and B to be the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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