ASP.NET MVC How safe are static variables ASP.NET MVC How safe are static variables asp.net asp.net

ASP.NET MVC How safe are static variables


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).


The static variables will be shared between requests.Moreover they will be initialized when application starts, so if the AppDomain, thus application gets restarted, their values will be reinitialized.