ASP.NET 状态管理(Application)

时间:2016-09-30 20:39:47   收藏:0   阅读:129

     转载自:http://www.cnblogs.com/SkySoot/archive/2012/07/13/2590256.html

 应用程序状态允许保存被所有客户访问的全局对象。应用程序状态基于 System.Web.HttpApplicationState 类,该类在 Web 页面中通过内建的 Application 对象提供。

       例如,可以创建一个 global.asax 事件处理程序来跟踪有多少会话被创建了,也可以使用相同的逻辑追踪某一页面的访问次数:

protected void Page_Load(object sender, EventArgs e)
{
    int count = 0;
    if (Application["HitCounterForOrderPage"] != null)
    {
        count = (int)Application["HitCounterForOrderPage"];
        count++;
        Application["HitCounterForOrderPage"] = count;
    }
}

       应用程序状态用对象类型保存状态项,所有集合中取值需要转换类型。应用程序状态中项目从不过期,一直被保存到应用程序或服务器重启。

 

       应用程序状态不太经常使用,因为效率不高。在上一个例子中,计数器的数字不精确,大量用户同时访问时,会丢失计数。为了避免这个情况的出现,可以使用 Lock()和 UnLock()方法,它们禁止用户同时访问 Application 集合:

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();
}

       遗憾的是,所有请求该页面的用户都将被暂停直到 Application 集合被释放。这会大大的降低性能。一般而言,经常改变的值不适合放到应用程序状态中。

 

       事实上,ASP.NET 中极少使用应用程序状态,因为它的两个最常用的功能已经被更简单,更有效的方法替代了:

 

静态应用程序变量

       还可以在 global.asax 文件中添加静态成员变量

public static string[] FileList;

       这能够起作用的关键在于变量时静态的。因为 ASP.NET 创建 HttpApplication 类的连接池来服务多个请求。这样,每次请求都可能由不同的 HttpApplication 对象来服务,每个 HttpApplication 对象都有自己的实例数据,然而,静态数据的副本只有一份。

       仍然存在多个页面会调用这个静态变量的可能性,但是由于不是 Application 对象因此没有了自动锁,所以应该使用 C# 的锁语句来临时将变量限定于某个单独的线程里

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];
    }
}

 

 

       使用静态成员变量而不使用 Application 集合有两大优势

private static string[] fileList;
public static string[] FileList
{
    get
    {
        if (fileList == null)
        {
            fileList = Directory.GetFiles(HttpContext.Current.Request.PhysicalApplicationPath);
        }
        return fileList;
    }
}
// 这个示例使用文件访问类来读取 Web 应用程序的文件列表
// 这个功能不可能通过 Application 集合实现

原文:http://www.cnblogs.com/Arlar/p/5924553.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!