How does the ThreadStatic attribute work?

后端 未结 4 662
余生分开走
余生分开走 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:40

    How does [ThreadStatic] attribute work?

    You can think that the field marked with ThreadStatic is attached to a thread and its lifetime is comparable to the lifetime of a thread.

    So in pseudocode ThreadStatic is similar (by semantics) to having a key-value attached to a thread:

    Thread.Current["MyClass.myVariable"] = 1;
    Thread.Current["MyClass.myVariable"] += 1;
    

    but the syntax is just a bit easier:

    class MyClass {
      [ThreadStatic]
      static int myVariable;
    }
    // .. then
    MyClass.myVariable = 1;
    MyClass.myVariable += 1;
    

    what happens if you put it on a non-static member?

    I believe it is ignored:

        class A {
            [ThreadStatic]
            public int a;
        }
        [Test]
        public void Try() {
            var a1 = new A();
            var a2 = new A();
            a1.a = 5;
            a2.a = 10;
            a1.a.Should().Be.EqualTo(5);
            a2.a.Should().Be.EqualTo(10);
        }
    

    Additionally it is worth mentioning that ThreadStatic does not require any synchronisation mechanism as compared to normal static fields (because the state is not shared).

提交回复
热议问题