user496949
user496949

Reputation: 86055

Thread local storage

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

Upvotes: 42

Views: 23517

Answers (4)

Ali Ferhat
Ali Ferhat

Reputation: 2579

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.

Upvotes: 61

James Kovacs
James Kovacs

Reputation: 11651

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

[ThreadStatic]
private static int foo;

Upvotes: 46

Conrad Frix
Conrad Frix

Reputation: 52645

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

Upvotes: 19

AdamSane
AdamSane

Reputation: 2882

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.

Upvotes: 8

Related Questions