简体   繁体   English

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

[英]Thread safe global variable in an ASP.Net MVC application

I need to implement a multi-threaded global variable in my ASP.Net MVC application. 我需要在我的ASP.Net MVC应用程序中实现多线程全局变量。

A ConcurrentDictionary<T> would be ideal but how do I make this accessible to every user session in my application? ConcurrentDictionary<T>是理想的选择,但是如何使应用程序中的每个用户会话都可以访问它呢?

Would something like this do the trick? 这样的事情会成功吗?

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

I need multiple users to be able to read and write to/from this object. 我需要多个用户才能读写该对象。

You can use HttpContext.current.Application for that like following 您可以使用HttpContext.current.Application这样的

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 使用静态变量not属性编辑您的静态类,如下所示

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 现在在您的global.aspx Application_Start事件中使用新对象设置该变量,如下所示

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 是的,ConcurrentDictionary和静态变量在.net应用程序中都是线程安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM