7.11. Managing State: The Application Object

There is analogous support for maintaining values across sessions within the Application object. The Global class provides a skeletal definition of an Application_Start() event handler. It is invoked once at the start of the application. This is where we initialize global data for our application. For example, let's provide values to hold total mouse clicks across all sessions:

protected void
Application_Start(Object sender, EventArgs e)
{
      Application.Add( "TotalAnnaCount", 0 );
      Application.Add( "TotalPoohCount", 0 );
      Application.Add( "TotalMissCount", 0 );
}

These values can be accessed concurrently through multiple sessions, so we need to be more careful when writing them. For example, the following read and write operation of the AnnaCount value:

Application[ "AnnaCount" ] =
            (int) Application[ "AnnaCount" ] + 1;

is potentially unsafe because a concurrent access may occur between the read and assignment of the value. A safer implementation provides a lock to ensure an atomic read/write operation:

Application.Lock(); // locks entire Application object
Application[ "AnnaCount" ] =
             (int) Application[ "AnnaCount" ] + 1;
Application.Unlock();

We might access this variable as follows within Page_Load():

private void Page_Load(object sender, System.EventArgs e)
{
    if ( ! this.IsPostBack )
         Label7.Text =
            "Total Anna Hits Prior to This Session: " +
             Application[ "AnnaCount" ].ToString();
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243