"asp.net mvc how safe are static variables" Code Answer


your code is not thread safe. you are sharing static variables between multiple requests which could potentially be executed by multiple threads. bear in mind that the dictionary<tkey, tvalue> class that you are using as underlying storage is not a thread safe class meaning that your code could potentially crash very badly if you attempt to call the onappinit method concurrently from multiple threads. if on the other hand you are calling this onappinit static method only once inside your application_start event (which is guaranteed to run only once from a single thread) you are pretty safe to use it there.

this being said saying that static variables and methods are generally a bad idea in applications is not true. they are a bad idea if you don't know how to use them properly, or if you don't know how to synchronize the access to them if you need this to be done from concurrent threads. writing thread-safe code is a very difficult subject and if you have fears to make it wrong (who doesn't when writing multithreaded applications such as an asp.net application?) simply do not share state like this. use the well established places for this in an asp.net application:

  • backend (could be a relational database for example)
  • application state
  • cache
  • http context state
  • session state
  • client cookies

those places are specifically designed for storing state in an asp.net application (except the first one of course which could be used in any type of application).

By Ah Cheng on February 19 2022

Answers related to “asp.net mvc how safe are static variables”

Only authorized users can answer the Search term. Please sign in first, or register a free account.