I need to implement a multi-threaded global variable in my ASP.Net MVC application.
A ConcurrentDictionary
would be ideal but how do I make thi
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