ThreadStatic Modified with Static C#
Asked Answered
M

3

54

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?

Mulkey answered 15/5, 2009 at 12:57 Comment(1)
+1 for good question. I'd never thought of this.Relict
S
58

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.

Soma answered 15/5, 2009 at 13:0 Comment(3)
Anyone aware of any documentation that describes the official policy on what it's supposed to do? If it is not supposed to be used in this way shouldn't it cause a compile error, or can attributes not cause compile errors?Interdigitate
It would be great if it were a compiler error, because I've just spent a couple of hours tracking a mysterious threading-related bug, which turned out to be due to [ThreadStatic] being used on an instance field and thus having no effect...Rufena
Just remember though, the ThreadPool shares threads (and ThreadStatic) across several tasks. You want to make sure the parallel task you are running is not running in a thread from the ThreadPool.Lunneta
A
9

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

Aryanize answered 15/5, 2009 at 12:59 Comment(0)
A
6

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.

Alburg answered 15/5, 2009 at 13:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.