ASP.Net MVC应用程序中的线程安全全局变量
我需要在ASP.Net MVC应用程序中实现一个multithreading全局变量。
ConcurrentDictionary
是理想的,但如何让我的应用程序中的每个用户会话都可以访问它?
这样的事情可以做到吗?
public static class GlobalStore { public static ConcurrentDictionary GlobalVar { get; set; } }
我需要多个用户才能读取和写入此对象。
您可以像下面这样使用HttpContext.current.Application
创建对象
HttpContext.Current.Application["GlobalVar"] = new ConcurrentDictionary();
获取或使用对象
ConcurrentDictionary GlobalVar = HttpContext.Current.Application["GlobalVar"] as ConcurrentDictionary;
编辑:
使用静态变量编辑静态类,而不是像下面这样的属性
public static class GlobalStore { public static ConcurrentDictionary GlobalVar; }
现在在global.aspx Application_Start事件中使用new对象设置该变量,如下所示
GlobalStore.GlobalVar = new ConcurrentDictionary();
然后你可以在你的应用程序中使用它
GlobalStore.GlobalVar["KeyWord"] = new DateTime(); DateTime obj = GlobalStore.GlobalVar["KeyWord"] as DateTime;
是的ConcurrentDictionary以及静态变量在.net应用程序中是线程安全的