简体   繁体   中英

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.

A ConcurrentDictionary<T> would be ideal but how do I make this accessible to every user session in my application?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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