简体   繁体   中英

What are static C# class variables for in ASP.NET?

I know what static class variables do in a C++ class, what I'm not very clear about is the life-cycle of static class variables in a C# class used for an ASP.NET web app. Here's a code example:

namespace MyWebApp
{
    public static class MyFunctions
    {
        private static string _cachedID;

        public static string getID(string strValue)
        {
            if(_cachedID == null)
                _cachedID = strValue;

            return _cachedID;
        }
    }
}

Can someone explain it in plain English for me?

I've read somewhere.

A static variable/field comes into existence before execution of the static constructor for its containing type, and ceases to exist when the associated application domain ceases to exists.

Since you are asking this question in the context of a multithreaded ASP.NET application, you should be extremely careful. Checkout the following scenario:

2 users Bob and Alice call the getID method at exactly the same time passing different arguments. Bob passes Foo and Alice passes Bar . Since this is the first call, the _cachedID variable is not yet initialized so both enter the if condition, Bob with a slight delay. So Alice sets the _cachedID static variable to Bar and a microsecond after, Bob sets it to Foo . Now the code continues and the function returns Foo for both users. Bob of course is happy because that's what he wanted, but Alice wanted Bar .

For example if you wanted to perform a one time initialization in a multithreaded environment you might consider using the thread safe version of the Singleton Pattern .

The moral of this is that you should be extremely careful when dealing with shared/static data in an ASP.NET application. If you need to use it you need to properly synchronize the access to it or very bad things could happen. And they usually happen in production when your application is concurrently accessed by multiple users. On your local PC everything will work fine.

And back to your original question about the lifetime of a static fields: it is tied to the lifetime of the application domain.

Classes which you can't and dont have to make an object of but you can only acces it from a static context.

you would use your example like this:

MyFunctions.getID("bla");

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM