2

我已经创建了 3 个线程,并且所有线程都对 thread1 之外的 threadlocal 属性进行了增量操作。我还在 threadlocal 委托中通过值 11 初始化 threadstatic 属性。这里我总是在第一个线程中获得 num = 0 的值。为什么这样?

class Program
    {
        //static int numDuplicate = 0;
        [ThreadStatic]
        static int num = 5;

        public static ThreadLocal<int> _field = new ThreadLocal<int>(() =>
        {
            num = 11;
            //numDuplicate = num;
            Console.WriteLine("Threadstatic variable value in Threadlocal's delegate = " + num.ToString());
            return Thread.CurrentThread.ManagedThreadId;
        });



        public static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(() =>
            {
                Console.WriteLine("Threadlocal attribute value for thread 1: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            Thread t2 = new Thread(new ThreadStart(() =>
            {
                _field.Value++;
            Console.WriteLine("Threadlocal attribute value for thread 2: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            Thread t3 = new Thread(new ThreadStart(() =>
            {
                _field.Value++;
                Console.WriteLine("Threadlocal attribute value for thread 3: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            t1.Start();
            t2.Start();
            t3.Start();
            Console.ReadLine();
        }
    }

//Output:
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadlocal attribute value for thread 1: 10. Threadstatic variable value = 0
Threadlocal attribute value for thread 3: 13. Threadstatic variable value = 11
Threadlocal attribute value for thread 2: 12. Threadstatic variable value = 11
4

1 回答 1

2

因为“不能”为 ThreadStatics 分配初始值。

不要为标有 ThreadStaticAttribute 的字段指定初始值,因为这样的初始化只发生一次,当类构造函数执行时,因此只影响一个线程。如果不指定初始值,则可以依赖正在初始化的字段(如果它是值类型)为其默认值,或者如果它是引用类型则为 null。

资料来源:MSDN


你可以看看ThreadLocal<>

static ThreadLocal<int> num  = new ThreadLocal<int>(() => 5);

Func<>作为每个新线程的初始化执行。在这种情况下,它只返回 5。

于 2016-12-22T09:02:06.237 回答