.net 公共变量 线程安全

项目场景:

比如一个仓储系统,可以切换仓房 ,每个仓房对接的设备链接不同 ,需要获取当前仓房的链接

这时候就需要一个公共量来表示这个链接,方便后续在不同的接口里调用,当多个用户操作这个系统时,需要保证这个公共量是当前用户操作的仓房链接


解决方案:

ConcurrentDictionary 这个可以有效保证线程安全

cs 复制代码
using Xhxx.Authorize;
using System.Configuration;
using System.Web.Http;
using Xhxx.Entity;
using ES.Web.Api;
using System.Net.Http;
using System.Web;
using System.Collections.Concurrent;

namespace System.Linq
{
#if DEBUG
    [AllowAnonymous]
#endif
    public class NBBaseController : BaseController
    {
       

        private static readonly ConcurrentDictionary<string, string> WmsUrlDic = new ConcurrentDictionary<string, string>();
//当前仓发链接
        public  string CurrentWmsUrl
        {
            get {
                return WmsUrlDic.GetOrAdd(base.loginerBase.UserCode ?? "super","");
            }
            set {
                WmsUrlDic.AddOrUpdate(base.loginerBase.UserCode ?? "super", value, (k, v) => value);

            }
        }
        public NBBaseController()
        {
           
        }

       
        protected void GetCruentWmsUrl(string StoreHouseCode)
        {

            lock (_locker)
            {
         
                switch (StoreHouseCode)
                {
                    case "913302001440687412007":
                        WmsUrlDic.TryUpdate(base.loginerBase.UserCode ?? "super", ConfigurationManager.AppSettings["WmsUrl"], CurrentWmsUrl);
                        break;
                    case "913302001440687412036":
                        WmsUrlDic.TryUpdate(base.loginerBase.UserCode ?? "super", ConfigurationManager.AppSettings["WmsLkUrl"], CurrentWmsUrl);
                        break;
                    default:
                        WmsUrlDic.TryUpdate(base.loginerBase.UserCode ?? "super", "", CurrentWmsUrl);
                        break;

                }
            }
           
          

        }

    }

  

      
    }
}
相关推荐
步步为营DotNet11 小时前
深挖.NET 11:.NET Aspire 在云原生应用韧性架构构建的探索与实践
云原生·架构·.net
rick97711 小时前
C# ModuleInitializer:程序集级别的初始化黑科技
.net
公子小六1 天前
基于.NET的Windows窗体编程之WinForms打印
windows·microsoft·c#·.net·winforms
light blue bird1 天前
可更新组装工序资源图表功能组件
开发语言·前端·jvm·.net·状态模式
步步为营DotNet1 天前
深入.NET 11:ASP.NET Core 10 在构建高可用分布式系统的关键技术与实践
asp.net·.net·wpf
步步为营DotNet2 天前
探索.NET 11:.NET Aspire 在云原生微服务治理中的创新实践
微服务·云原生·.net
学以智用2 天前
.NET Core 数据验证(最全实战指南)
后端·.net
无风听海3 天前
.NET 10 Claim 身份体系深度解析
.net
周杰伦fans3 天前
不支持目标框架: C#项目面向不再受支持的.NET Framework4.6.2
开发语言·c#·.net
喵叔哟3 天前
12.【.NET10 实战--孢子记账--产品智能化】--技术选型
.net