c# - ASP.Net MVC 应用程序中的线程安全全局变量

标签 c# asp.net multithreading asp.net-mvc-4

我需要在 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/

相关文章:

java - 简单的java线程测试程序不起作用

multithreading - Delphi中的跨线程通信

c# - 一对多关系不起作用 - Entity Framework

c# - 委托(delegate)中的方法参数

javascript - 使用 css 和 javascript 突出显示单击文本框 div

ASP.NET AJAX CalendarExtender - Android 浏览器问题

c# - ASP.net WebApi 发现与 URL 匹配的多个 Controller 类型

c# - 未处理的异常错误缺少 resx

c# - XAML 和 C# 代码背后的 UI 区别

java - 在 android Activity 中播放重复的 AudioTrack