ASP. NET state Management (application)

Source: Internet
Author: User

Reprinted from: http://www.cnblogs.com/SkySoot/archive/2012/07/13/2590256.html

Application state allows you to save global objects that are accessed by all clients. Application state is based on the System.Web.HttpApplicationState class, which is provided in the Web page through the built-in application object.

For example, you can create a Global.asax event handler to track how many sessions have been created, or you can use the same logic to track the number of visits to a page:

protected void Page_Load (object sender, EventArgs e)
{
    int count = 0;
    if (application["Hitcounterfororderpage"]! = NULL)
    {
        Count = (int) application["Hitcounterfororderpage"];
        count++;
        application["Hitcounterfororderpage"] = count;
    }
}

Application state holds state items with object types, and values in all collections require conversion types. An item in application state never expires and is saved to an application or server restart.

Application state is not used very often because it is inefficient. In the previous example, the number of counters is inaccurate, and when a large number of users concurrently access it, the count is lost. To avoid this situation, you can use the Lock () and UnLock () methods, which prohibit users from accessing the application collection at the same time:

protected void Page_Load (object sender, EventArgs e)
{
    Application.Lock ();
    int count = 0;
    if (application["Hitcounterfororderpage"]! = NULL)
    {
        Count = (int) application["Hitcounterfororderpage"];
        count++;
        application["Hitcounterfororderpage"] = count;
    }
    Application.UnLock ();
}

Unfortunately, all users who request the page will be paused until the application collection is freed. This can greatly degrade performance . Generally, values that change frequently do not fit into the application state.

In fact, the application state is rarely used in ASP. Two of its most commonly used features have been replaced by simpler, more efficient methods:

    • Previously, people used application state to hold application-level constants, such as database connection strings. This type of constant can now be stored in Web. config, which is usually more flexible because it is easy to modify without needing to change the code or recompile the application.
    • application state can also be used to save frequently used but to create more time-consuming information, such as database queries for all product catalogs. But now more similar, it's wise to keep common information in the ASP. NET Cache. Many applications of application state can use the cache to effectively replace .

Static Application variables

You can also add static member variables in the Global.asax file:

Public static string[] FileList;

The key to this function is the static variable. Because ASP. NET creates a connection pool for the HttpApplication class to serve multiple requests. In this way, each request may be serviced by a different HttpApplication object, each HttpApplication object has its own instance data, however, there is only one copy of the static data.

there is still a possibility that multiple pages will invoke this static variable, but since it is not an Application object and therefore does not have an automatic lock, a C # lock statement should be used to temporarily limit the variable to a separate line thread .

private static dictionary<string, string> metadata = new dictionary<string, string> ();
public void Addmetadata (string key, String value)
{
    Lock (metadata)
    {
        Metadata[key] = value;
    }
}
public string GetMetaData (string key)
{
    Lock (metadata)
    {
        return Metadata[key];
    }
}

There are two major advantages to using static member variables instead of using the application collection .

    • First, when a value is accessed or modified (by binding data in a Property procedure or method), it allows you to write code that can be run automatically. You can use this code to record how many times a value has been accessed, to check whether the data is still valid, or if it needs to be recreated. This example uses deferred initialization mode and creates a global object only on the first request:
private static string[] fileList;
public static string[] FileList
{
    Get
    {
        if (fileList = = null)
        {
            FileList = Directory.GetFiles (HttpContext.Current.Request.PhysicalApplicationPath);
        }
        return fileList;
    }
}
This example uses the file access class to read the file list of a WEB application
This feature is not possible with the application collection
    • Another benefit of using static member variables is type safety, and the variable types obtained from the Global class do not need to be converted.

ASP. NET state Management (application)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.