36

what is the best way to store some variable local to each thread?

user496949
  • 79,431
  • 144
  • 301
  • 419

4 Answers4

53

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
  • 94,937
  • 19
  • 203
  • 272
Ali Ferhat
  • 2,443
  • 16
  • 24
41

You can indicate that static variables should be stored per-thread using the [ThreadStatic] attribute:

[ThreadStatic]
private static int foo;
Sam Harwell
  • 94,937
  • 19
  • 203
  • 272
James Kovacs
  • 11,419
  • 37
  • 44
  • 1
    Can 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 { 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. – RBT Jun 01 '17 at 02:02
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
  • 48,897
  • 65
  • 188
  • 331
Conrad Frix
  • 50,756
  • 12
  • 89
  • 148
  • 3
    Does 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,812
  • 1
  • 23
  • 28