Using HttpContext.Current.Application to store simple data

后端 未结 5 1055
旧时难觅i
旧时难觅i 2020-12-09 19:02

I want to store a small list of a simple object (containing three strings) in my ASP.NET MVC application. The list is loaded from the database and it is updated rarely by ed

5条回答
  •  时光取名叫无心
    2020-12-09 19:32

    Yes, using HttpContext.Current.Application will work fine for what you are doing. No problems.

    HttpContext.Current.Application is simply a reference to the static global HttpApplicationState object in .NET for your Web Application, of which there should be one global instance per web application. By storing data there, you provide fast, thread-safe access to your global variables. Be sure to lock them when updating values, as in this example:

    System.Web.HttpContext.Current.Application.Lock();
    System.Web.HttpContext.Current.Application["WebApplicationPath"] = MyWebApplicationPath;
    System.Web.HttpContext.Current.Application.UnLock();
    

    As others have mentioned, you can also create a series of static classes in your App_Code or other folder and there store global static values as well as your HttpContext.Current.Application values, where they can be safely checked for values or updated from the database, or update and check each other, working in tandem. I usually create a static global class to assist in the management and retrieval of the Application variables I store. In this way you have both the state dictionary of the HttpApplicationState class and the web application static objects working together to share and maintain global values. (Keep in mind each static class is assigned per worker process and there may be as many as 10 WP on average by default on many IIS web servers/web applications. So keep data in static types to a minimum.)

    Keep in mind as some mentioned server farms do not share Application state. There are many ways to manage this. I'm not a fan of cache because of the ways in which it can expire, fail, become stale, or get corrupted. A simpler solution is to simply use use the database and URL querystrings to communicate across servers and maintain state. Good luck!

提交回复
热议问题