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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…