Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadStatic Modified with Static C#

I have some code where I use a thread static object in C#.

[ThreadStatic]
private DataContext connection 

I was wondering, in this case, what if any change would I get if I put the static modifier on the thread static context?

[ThreadStatic]
private static DataContext connection 

With the first would there be one copy of the context per instance per thread, with the other only one copy per thread?

like image 667
Anthony D Avatar asked May 15 '09 12:05

Anthony D


3 Answers

The ThreadStaticAttribute is only designed to be used on static variables, as the documentation points out. If you use it on an instance variable, I suspect it will do precisely nothing.

like image 152
Noldorin Avatar answered Nov 02 '22 10:11

Noldorin


In the first case it would probably be ignored, whereas in the second case you are correct, one instance per thread.

like image 9
Otávio Décio Avatar answered Nov 02 '22 11:11

Otávio Décio


In Microsoft Docs, it says:

Indicates that the value of a static field is unique for each thread.

So I guess your first case is incorrect. The attribute will probably be ignored.

like image 6
Thomas Levesque Avatar answered Nov 02 '22 09:11

Thomas Levesque