【问题标题】:Why Initializing threadstatic attribute in Threadlocal delegate doesn't initilize it for the first thread?为什么在 Threadlocal 委托中初始化 threadstatic 属性不会为第一个线程初始化它?
【发布时间】:2017-05-07 20:00:21
【问题描述】:

我已经创建了 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

【问题讨论】:

    标签: c# multithreading threadstatic


    【解决方案1】:

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

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

    来源:MSDN


    你可以看看ThreadLocal&lt;&gt;

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

    Func&lt;&gt; 将作为每个新线程的初始化执行。在这种情况下,它只返回 5。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2019-06-18
      相关资源
      最近更新 更多