I have a static variable which is accessed by multiple threads in multiple object. The problem is if I set value in one thread it does not reflect in another thread. To resolve the issue I made the variable thread static but still the value changed in one thread does to reflect in another thread. That’s how I declared the variable:
[ThreadStatic]
public static string ThreadVar;
Any suggestion on how to resolve the issue?
The compiler and JIT are free to assume that fields will not be changed by multiple threads, and can optimize away re-fetches of the same field if it is provable that the value cannot be changed by the current thread between fetches.
Marking the field
volatile
communicates the opposite: that you expect the field to be changed by external forces (including other threads) and that the compiler/JIT must not optimize away any re-fetches.Note that marking the field
volatile
does not immediately mean that all usage of the field is thread-safe, it only means that one thread will notice when a new value is written to the field by another thread. We would need to see more of your code to determine if there is a thread safety issue.[ThreadStatic]
, in comparison, tells the compiler that each thread should have its own copy of the variable, which based on your question is not at all what you want.