C# : What if a static method is called from multiple threads?

Variables declared inside methods (with the possible exception of “captured” variables) are isolated, so you won’t get any inherent problems; however, if your static method accesses any shared state, all bets are off.

Examples of shared-state would be:

  • static fields
  • objects accessed from a common cache (non-serialized)
  • data obtained via the input parameters (and state on those objects), if it is possible that multiple threads are touching the same object(s)

If you have shared state, you must either:

  • take care not to mutate the state once it can be shared (better: use immutable objects to represent state, and take a snapshot of the state into a local variable – i.e. rather than reference whatever.SomeData repeatedly, you read whatever.SomeData once into a local variable, and then just use the variable – note that this only helps for immutable state!)
  • synchronize access to the data (all threads must synchronize) – either mutually exclusive or (more granular) reader/writer

Leave a Comment