4

I want to store some info (key value pair) in a c# thread context or similar ( just like httpcontext for a web request ).

I want to be able to store this info (key value pair) somewhere in thread context ( or something similar) so that my code can always read these values from the current thread its running under.

In my appliation i have a chain of API calls and its not possible to pass this info from one method to other ( already dsicarded this option! )

note - this thread is running as an async operation inside an Asp.Net application.

dotnetcoder
  • 3,431
  • 9
  • 54
  • 80

1 Answers1

4

Are you looking for Thread Local storage using the ThreadStatic attribute ?

public static class ThreadLocalExample
{
    // There will be one Foo instance per thread.
    // Each thread will have to initialize it's own instance.
    [ThreadStatic]
    private static Foo bar;
}

Of course you could add some helper methods or properties to the above to help you manage the instance, including ensuring initialization on each thread.

Chris Taylor
  • 52,623
  • 10
  • 78
  • 89
driis
  • 161,458
  • 45
  • 265
  • 341