what is the best way to store some variable local to each thread?
Asked
Active
Viewed 2.0k times
4 Answers
57
If you use .Net 4.0 or above, as far as I know, the recommended way is to use System.Threading.ThreadLocal<T>
which also gives lazy initialization as a bonus.

Sam Harwell
- 97,721
- 20
- 209
- 280

Ali Ferhat
- 2,511
- 17
- 24
-
10This method is also not limited to static fields. – Sam Harwell Jun 03 '13 at 15:37
44
You can indicate that static variables should be stored per-thread using the [ThreadStatic]
attribute:
[ThreadStatic]
private static int foo;

Sam Harwell
- 97,721
- 20
- 209
- 280

James Kovacs
- 11,549
- 40
- 44
-
1Can I store static List of objects per-thread with this attribute? – Dainius Kreivys Oct 26 '16 at 13:22
-
4@DainiusKreivys Yes! No matter what the type of variable is, its unique instance will be maintained per thread as long as you are using `[ThreadStatic]` attribute. I did a quick test using `[ThreadStatic] private static List
foo = new List – RBT Jun 01 '17 at 02:02{ 20, 30 };`. Then, on another thread I initialized the same foo variable with a list containing three integers and when that thread ended my original list containing two elements referred by main thread remained intact.
19
Another option in the case that scope is an issue you can used Named Data Slots e.g.
//setting
LocalDataStoreSlot lds = System.Threading.Thread.AllocateNamedDataSlot("foo");
System.Threading.Thread.SetData(lds, "SomeValue");
//getting
LocalDataStoreSlot lds = System.Threading.Thread.GetNamedDataSlot("foo");
string somevalue = System.Threading.Thread.GetData(lds).ToString();
This is only a good idea if you can't do what James Kovacs and AdamSane described

NibblyPig
- 51,118
- 72
- 200
- 356

Conrad Frix
- 51,984
- 12
- 96
- 155
-
3Does named data slots work with the new `async Task` model? Is there something extra needed to make a slot available in the task? – Jaans Nov 13 '14 at 10:20
-
@Jaans See https://stackoverflow.com/questions/23555255/how-to-maintain-thread-context-across-async-await-model-in-c – Dai Nov 16 '21 at 09:04
7
Other option is to pass in a parameter into the thread start method. You will need to keep in in scope, but it may be easier to debug and maintain.

AdamSane
- 2,831
- 1
- 24
- 28