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