ThreadStatic Modified with Static C#

C#StaticThread Static

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony DView Question on Stackoverflow
Solution 1 - C#NoldorinView Answer on Stackoverflow
Solution 2 - C#Otávio DécioView Answer on Stackoverflow
Solution 3 - C#Thomas LevesqueView Answer on Stackoverflow