我需要在 ASP.Net MVC 应用程序中实现多线程全局变量。
一个ConcurrentDictionary<T>
这将是理想的选择,但如何使应用程序中的每个用户 session 都可以访问它?
像这样的东西会起作用吗?
public static class GlobalStore
{
public static ConcurrentDictionary<string, DateTime> GlobalVar { get; set; }
}
我需要多个用户才能读取和写入此对象。
最佳答案
您可以使用 HttpContext.current.Application 来实现,如下所示
创建对象
HttpContext.Current.Application["GlobalVar"] = new ConcurrentDictionary<string, DateTime>();
获取或使用对象
ConcurrentDictionary<string, DateTime> GlobalVar = HttpContext.Current.Application["GlobalVar"] as ConcurrentDictionary<string, DateTime>;
编辑:
使用静态变量而不是属性编辑静态类,如下所示
public static class GlobalStore
{
public static ConcurrentDictionary<string, DateTime> GlobalVar;
}
现在在 global.aspx Application_Start 事件中使用新对象设置该变量,如下所示
GlobalStore.GlobalVar = new ConcurrentDictionary<string, DateTime>();
然后您可以通过以下方式在您的应用程序中使用它
GlobalStore.GlobalVar["KeyWord"] = new DateTime();
DateTime obj = GlobalStore.GlobalVar["KeyWord"] as DateTime;
是的,ConcurrentDictionary 以及静态变量在 .net 应用程序中都是线程安全的
关于c# - ASP.Net MVC 应用程序中的线程安全全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20347280/