线程安全的全局变量在ASP.Net MVC应用程序 [英] Thread safe global variable in an ASP.Net MVC application

查看:504
本文介绍了线程安全的全局变量在ASP.Net MVC应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的ASP.Net MVC应用程序来实现一个多线程的全局变量。

I need to implement a multi-threaded global variable in my ASP.Net MVC application.

A ConcurrentDictionary< T> 将是理想的,但我怎么做这个访问的每个用户会话在我的应用

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

应该是这样做的伎俩?

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.

推荐答案

您可以使用HttpContext.current.Application的,像下面的

You can use HttpContext.current.Application for that like following

要创建对象

HttpContext.Current.Application["GlobalVar"] = new ConcurrentDictionary<string, DateTime>();

要获取或使用对象

ConcurrentDictionary<string, DateTime> GlobalVar = HttpContext.Current.Application["GlobalVar"] as ConcurrentDictionary<string, DateTime>;

编辑:

编辑静态类静态变量不是像财产以下

Edit your static class with static variable not property like following

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

现在设置新的对象变量您global.aspx Application_Start事件类似以下

Now set that variable with new object in you global.aspx Application_Start event like following

GlobalStore.GlobalVar = new ConcurrentDictionary<string, DateTime>();

然后你可以通过

    GlobalStore.GlobalVar["KeyWord"] = new DateTime();
DateTime obj = GlobalStore.GlobalVar["KeyWord"] as DateTime;

和是ConcurrentDictionary以及静态变量在.NET应用程序的线程安全的。

And yes ConcurrentDictionary as well as static variables are thread safe in .net applications

这篇关于线程安全的全局变量在ASP.Net MVC应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆