Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Variables in WCF

Tags:

c#

asp.net

wcf

I have some WCF services. These services run in ASP.NET. I want these services to be able to access a static variable. My problem is, I'm not sure where the appropriate server level storage mechanism is. I don't want to use the database because of speed. But, I want the static variables to stay in memory as long as possible. In fact, I'd like it to stay until I restart my server if it all possible.

Can anyone provide me with any ideas?

like image 213
user609886 Avatar asked Feb 13 '11 13:02

user609886


2 Answers

You could use static variables in WCF but you must properly synchronize the access to them because they can potentially be accessed from multiple threads concurrently. The values stored in static variables are accessible from everywhere in the AppDomain and remain in memory until the server is restarted.

like image 102
Darin Dimitrov Avatar answered Oct 11 '22 03:10

Darin Dimitrov


You could have something like this

public static class StaticVariables
{
    private static string _variable1Key = "variable1";

    public static Object Variable1
    {
        get 
        {
            return Application[_variable1Key]; 
        }

        set 
        {
            Application[_variable1Key] = value; 
        }
    } 
}

The Application collection itself is thread safe but the stuff you add to it might not be; so keep that in mind.

like image 38
Bala R Avatar answered Oct 11 '22 05:10

Bala R