Take the 2-minute tour ×

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

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?

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?

share|improve this question
+1 for good question. I'd never thought of this. –  Greg D May 15 '09 at 12:59
Thanks for the edit itsmatt! –  Anthony D May 15 '09 at 13:06

3 Answers 3

up vote 36 down vote accepted

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

share|improve this answer
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? –  Catskul Jan 28 '10 at 23:41
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... –  romkyns Apr 10 '10 at 12:11
@romkyns same here... just nailed a bug caused by [ThreadStatic] on an instance field. –  chakrit Jun 30 '10 at 9:59
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. –  eduncan911 Jul 19 '12 at 12:35
+1 for the last sentence. –  Alireza Oct 28 '13 at 18:57

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

share|improve this answer

MSDN says :

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

So I guess you first case is incorrect... the attribute will probably be ignored

share|improve this answer

Your Answer


