store List in Global.asax

╄→гoц情女王★ 提交于 2019-12-22 12:34:13

问题


We can store application level strings in a global.asax file like: Global asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        Application["msg"] = "";            
        Application.UnLock();        
    }

And then in pages we get the "msg" variable as: a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
 {
        string msg = (string)Application["msg"];
        //manipulating msg..
 }

However, I want to store List of objects as application level variable instead of string msg. I tried this: Global.asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        List<MyClassName> myobjects= new List<MyClassName>();      
        Application.UnLock();        
    }

a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        //here I want to get myobjects from the global.asax and manipulate with it..
    }

So, how to store List myobjects as an application level variable in global.asax and work with this?

Moreover, I have another question: How to send any notification to clients(browsers) when global variable in global.asax is changed?


回答1:


One way would be to store it into the cache :

using System.Web.Caching;    

protected void Application_Start()
{
   ...
   List<MyClassName> myobjects = new List<MyClassName>();
   HttpContext.Current.Cache["List"] = myobjects;
}

then to access / manipulating it :

using System.Web.Caching;

var myobjects =  (List<MyClassName>)HttpContext.Cache["List"];
//Changes to myobjects
...
HttpContext.Cache["List"] = myobjects;


来源:https://stackoverflow.com/questions/12857899/store-list-in-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!