Thread safe global variable in an ASP.Net MVC application

前端 未结 1 1020
再見小時候
再見小時候 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();
    

    To get or use object

    ConcurrentDictionary GlobalVar = HttpContext.Current.Application["GlobalVar"] as ConcurrentDictionary;
    

    EDIT:

    Edit your static class with static variable not property like following

    public static class GlobalStore
    {
        public static ConcurrentDictionary GlobalVar;
    }
    

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

    GlobalStore.GlobalVar = new ConcurrentDictionary();
    

    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)
提交回复
热议问题