.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;

                }
            }
           
          

        }

    }

  

      
    }
}
相关推荐
Lost of 程序猿4 小时前
.NET 线程安全集合与并发数据结构深度实战:从 lock 到无锁
数据结构·安全·.net
rockey62716 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
陈珙1 天前
.NET AI 实战:用 MCP 把 Claude Code 变成数据库 DBA
架构·.net·技术
geovindu1 天前
CSharp: Template Method Pattern
开发语言·后端·c#·.net·模板方法模式·行为模式
步步为营DotNet1 天前
【MVP深度】.NET MAF:从单 Agent 到可恢复的多 Agent 工作流
.net
geovindu2 天前
CSharp: 万年历
开发语言·后端·c#·.net
用户298698530142 天前
PDF 转 HTML 全攻略:三种方法轻松搞定网页转换
c#·html·.net
geovindu2 天前
CSharp: State Pattern
开发语言·后端·c#·.net·状态模式·行为模式
2601_962064704 天前
【报表查询】.NET开源ORM框架 SqlSugar 系列
开源·.net