Thread safe global variable in an ASP.Net MVC application

前端 未结 1 1019
再見小時候
再見小時候 2021-01-15 15:02

I need to implement a multi-threaded global variable in my ASP.Net MVC application.

A ConcurrentDictionary would be ideal but how do I make thi

相关标签:
1条回答
  • 2021-01-15 15:32

    You can use HttpContext.current.Application for that like following

    To create object

    HttpContext.Current.Application["GlobalVar"] = new ConcurrentDictionary<string, DateTime>();
    

    To get or use object

    ConcurrentDictionary<string, DateTime> GlobalVar = HttpContext.Current.Application["GlobalVar"] as ConcurrentDictionary<string, DateTime>;
    

    EDIT:

    Edit your static class with static variable not property like following

    public static class GlobalStore
    {
        public static ConcurrentDictionary<string, DateTime> GlobalVar;
    }
    

    Now set that variable with new object in you global.aspx Application_Start event like following

    GlobalStore.GlobalVar = new ConcurrentDictionary<string, DateTime>();
    

    Then you can use it in your application by

        GlobalStore.GlobalVar["KeyWord"] = new DateTime();
    DateTime obj = GlobalStore.GlobalVar["KeyWord"] as DateTime;
    

    And yes ConcurrentDictionary as well as static variables are thread safe in .net applications

    0 讨论(0)
提交回复
热议问题