[英]Thread safe global variable in an ASP.Net MVC application
我需要在我的ASP.Net MVC應用程序中實現多線程全局變量。
ConcurrentDictionary<T>
是理想的選擇,但是如何使應用程序中的每個用戶會話都可以訪問它呢?
這樣的事情會成功嗎?
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>;
編輯:
使用靜態變量not屬性編輯您的靜態類,如下所示
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應用程序中都是線程安全的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.