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

                }
            }
           
          

        }

    }

  

      
    }
}
相关推荐
iReachers5 小时前
.NET项目集成混淆加密:自动化保护DLL和EXE
.net·代码保护·自动构建·msbuild·c#混淆
完美火龙篇 四月的友13 小时前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
柠檬香的15 小时前
CsGrafeq: 比 Desmos 更“能折腾”的几何函数画板(.NET + Avalonia)
.net
geovindu1 天前
CSharp: Iterative Algorithms
开发语言·后端·算法·c#·.net·迭代算法
geovindu4 天前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
驰骋工作流4 天前
请假流程:六款.NET工作流引擎实现方式对比
.net·ccflow·工作流引擎二开·.net工作流引擎对比
WarPigs4 天前
.NET项目app.Config笔记
c#·.net
海盗12345 天前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗12345 天前
微软技术日报 ——2026-07-21
microsoft·c#·.net
半亩码田5 天前
【.NET新特性·第8篇】.NET 9 AI 构建基块:Microsoft.Extensions.AI
人工智能·microsoft·.net