15

I have face a requirement,

I want client access a data center but without use database , so I want my web app can retain a global or Application session variable, that contains the data, every client can access the same data... I am try to declare in golabl, but seem it only can store String but others ...

how to solve this problem ?

thanks.

iXcoder
  • 1,564
  • 4
  • 20
  • 41
  • 2
    Are you referring to a session variable that will stay constant through the life of the session or a variable that will be shared between clients (other sessions)? – KennyH Nov 13 '10 at 05:28
  • Can you share the example you're trying to work with? – jcolebrand Nov 14 '10 at 01:52
  • See also http://stackoverflow.com/questions/20347280/thread-safe-global-variable-in-an-asp-net-mvc-application – Tony Apr 16 '16 at 15:41

5 Answers5

12

Another option of defining a global variable is by creating a static class with a static property:

public static class GlobalVariables
{
    public static string MyGlobalVariable { get; set; }
}

You can make this more complex if you are going to use this as a data store, but the same idea goes. Say, you have a dictionary to store your global data, you could do something like this:

public static class GlobalData
{
    private static readonly object _syncRoot = new object();
    private static Dictionary<string, int> _data;

    public static int GetItemsByTag(string tag)
    {
        lock (_syncRoot)
        {
            if (_data == null)
                _data = LoadItemsByTag();

            return _data[tag];
        }
    }

    private static Dictionary<string, int> LoadItemsByTag()
    {
        var result = new Dictionary<string, int>();

        // Load the data from e.g. an XML file into the result object.

        return result;
    }
}
Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
  • 2
    The static data is common only inside the pool, if some have many pools then they are different. – Aristos Nov 14 '10 at 12:57
  • @Aristos - It is static within the `AppDomain`. Is that the same as within the pool? – Pieter van Ginkel Nov 14 '10 at 13:00
  • 1
    @Pieter no the static is the same only inside the pool. If you have 2 pools then you have 2 different static value, and if a user, use both pools that is very possible, then the value is different. Make some tests to see it by your self. (you need iis6+) – Aristos Nov 15 '10 at 13:20
  • @Aristos - That's very interesting. I'm curious then what's the difference between a pool and an `AppDomain`. Do you know some documentation of that? – Pieter van Ginkel Nov 15 '10 at 13:56
  • @Aristos @Pieter yup it happened to me while using Web Garden. Took me and the team half day to figure it out.. :| – Shadow The GPT Wizard Nov 15 '10 at 14:04
  • 1
    @Pieter Look, the pool take care to run one AppDomain for one web site. You can have many web sites on the same pool, and you have many AppDomain for the same web site, each AppDomain in each pool. All that are not connected together. – Aristos Nov 15 '10 at 15:53
  • @Aristos - I get it now. I understood that the static variables were local to the AppDomain, and they are. But, you can have multiple AppDomain's for one website via multiple pools. Then, I am still wondering, the `Application[]` settings, these are shared between pools? – Pieter van Ginkel Nov 15 '10 at 15:58
  • @Pieter To tell you the truth I do not know to answer about Application[] and help from MS is not answer to that (at least I do not understand it). Need to be checked. We on our application we use database for having common data around all pools that running. – Aristos Nov 15 '10 at 20:19
  • @Aristos - No problem. I'll check for myself. Thanks for all the info. – Pieter van Ginkel Nov 15 '10 at 20:54
  • Static variables are shared by all users. If one users sets the static variable, all the users will see that values. – It's a trap Nov 29 '17 at 14:14
12

To Share the data with all application users, you can use ASP.NET Application object. Given is the sample code to access Application object in ASP.NET:

Hashtable htblGlobalValues = null;

if (Application["GlobalValueKey"] != null)
{
    htblGlobalValues = Application["GlobalValueKey"] as Hashtable;
}
else
{
    htblGlobalValues = new Hashtable();
}

htblGlobalValues.Add("Key1", "Value1");
htblGlobalValues.Add("Key2", "Value2");

this.Application["GlobalValueKey"] = htblGlobalValues;

Application["GlobalValueKey"] can be used anywhere in the whole application by any user. It will be common to all application users.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sankalp
  • 929
  • 1
  • 7
  • 16
  • 3
    Please stop adding signature blocks to your posts. They make it look like you're trying to spam your web site. There's a link to your profile on every post you make, which acts as your signature. You can add anything you like (within reason) to your profile page. That would be the place to post a link to your blog, web site, side projects, business, etc. – Bill the Lizard Nov 14 '10 at 01:43
  • You do excess lookup to Application – abatishchev Feb 25 '11 at 14:59
  • -1 for no thread-safe locking. See @Pieter's answer for an example of what to add. Whether using Application or a static class, it's still necessary. – CrazyPyro Aug 08 '14 at 16:32
2

You can stuff data into the Application object if you want. It isn't persistent across application instances, but that may sufficient.

(I'm not for a minute going to suggest this is a best practice, but without a clearer picture of the requirements, that's all I can suggest.)

http://msdn.microsoft.com/en-us/library/system.web.ui.page.application.aspx
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
1

If you are using WebApplication or MVC just go to Global.asax (in WebSite project you need to add Global.asax from the add new item menu).
I will explain to deploy two global variables for your web application:
Open the Global.asax file, then define your variable in Application_Start function as following:

void Application_Start(object sender, EventArgs e)
{
   Application.Lock();
   Application["variable1"] = "Some Value for variable1";
   Application["variable2"] = "Some Value for variable2";
   Application.UnLock();
}


If you want to use that those global variables in aspx pages just need to call them like this:

<p>I want to call variable1 <%=Application["variable1"].ToString() %></p>
<p>I want to call variable1 <%=Application["variable2"].ToString() %></p>


But if you want to use that those global variables in server-side call'em like this:

protected void Page_Load(object sender, EventArgs e)
{
   string str1 = Application["variable1"].ToString();
   string str2 = Application["variable2"].ToString();
}

Note: You must be aware that these global variables are public to all users and aren't suitable for authentication jobs.

Reza Paidar
  • 863
  • 4
  • 21
  • 51
0

You can also use Cache, which has advantages like ability to set expire time/date.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208