Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - How does the ThreadStatic attribute work?

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 doesn't seem to do it at that level.

As a follow up, what happens if you put it on a non-static member? We had a developer make that mistake and the compiler doesn't even proffer up a warning.

Update

Second question answered here: ThreadStatic Modified with Static C#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...