Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC How safe are static variables

I want to ensure my website is capable of being hosted on the cloud in the future and also that it can handle a lot of requests.

How safe are static variables?

Are they unsafe because separate requests by separate users are actually sharing these static variables? Or is it because if you spread the site over threads/sharding or similar, (to handle high loads) the threads are sharing the static variables?

Mainly I have helper classes, with static properties, should I change this architecture so that I instead create an instance of each class and access the instances?

E.G Here is a sample of what I am doing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;

namespace MVCWebsite.Helpers
{
        public class AppSettings
        {
                public static void OnAppInit()
                {
                        //General
                        AppName = "MyApp";
                        DesktopBaseURLs = new Dictionary<string, string>();
                        DesktopBaseURLs.Add("dev", "localhost:50560");
                        DesktopBaseURLs.Add("test", "www.test.whatever.com");
                        DesktopBaseURLs.Add("live", "www.whatever.com");
                        MobileBaseURLs = new Dictionary<string, string>();
                        MobileBaseURLs.Add("dev", "m.local.whatever.com");
                        MobileBaseURLs.Add("test", "m.test.whatever.com");
                        MobileBaseURLs.Add("live", "m.whatever.com");

                        //Emails
                        EmailHostName = AppName + ".com"; //For the moment atleast
                        NoReplyEmailAddress = "no-reply@" + EmailHostName.ToLower();
                        SupportEmailAddress = "support@" + EmailHostName.ToLower();
                        ErrorEmailAddress = "errors@" + EmailHostName.ToLower();

                        //Resources
                        TempFileURL = "/content/temp/";
                        UserDataURL = "/content/user-content/";
                        ProfilePicturesURL = UserDataURL + "profile-pictures/";

                        var a = GlobalHelper.GetURLAsServerPath(ProfilePicturesURL);
                        var b = a;

                }

                //General
                public static string AppName { get; set; }
                public static Dictionary<string, string> DesktopBaseURLs;
                public static Dictionary<string, string> MobileBaseURLs;

                //Emails
                public static string EmailHostName { get; set; }
                public static string NoReplyEmailAddress { get; set; }
                public static string SupportEmailAddress { get; set; }
                public static string ErrorEmailAddress { get; set; }

                //Resources
                public static string UserDataURL { get; set; }
                public static string TempFileURL { get; set; }
                public static string ProfilePicturesURL { get; set; }

                //Methods
                public static void SetAppURL()
                {

                }
        }
}
like image 989
williamsandonz Avatar asked Jan 08 '13 22:01

williamsandonz


People also ask

Are static variables safe?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.

Is it good to use static variables in C#?

Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.

Why static variable should not be used?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

How long does a static variable last C#?

A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.


Video Answer


2 Answers

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

like image 104
Darin Dimitrov Avatar answered Oct 21 '22 00:10

Darin Dimitrov


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.

like image 23
Sebastian K Avatar answered Oct 20 '22 23:10

Sebastian K