How does the ThreadStatic attribute work?

后端 未结 4 658
余生分开走
余生分开走 2020-12-04 07:47

How does [ThreadStatic] attribute work? I assumed that the compiler would emit some IL to stuff/retrieve the value in the TLS, but looking at a disassembly it d

4条回答
  •  隐瞒了意图╮
    2020-12-04 08:39

    The [ThreadStatic] creates isolated versions of the same variable in each thread.

    Example:

    [ThreadStatic] public static int i; // Declaration of the variable i with ThreadStatic Attribute.
    
    public static void Main()
    {
        new Thread(() =>
        {
            for (int x = 0; x < 10; x++)
            {
                i++;
                Console.WriteLine("Thread A: {0}", i); // Uses one instance of the i variable.
            }
        }).Start();
    
        new Thread(() =>
       {
           for (int x = 0; x < 10; x++)
           {
               i++;
               Console.WriteLine("Thread B: {0}", i); // Uses another instance of the i variable.
           }
       }).Start();
    }
    

提交回复
热议问题