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

                }
            }
           
          

        }

    }

  

      
    }
}
相关推荐
唐青枫1 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20107 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
追逐时光者19 小时前
.NET Fiddle:一个方便易用的在线.NET代码编辑工具
后端·.net
mudtools21 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
追逐时光者1 天前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
私人珍藏库2 天前
[Windows] 微软 .Net 运行库离线安装包 | Microsoft .Net Packages AIO_v09.09.25
microsoft·.net·运行库
追逐时光者2 天前
C#/.NET/.NET Core技术前沿周刊 | 第 54 期(2025年9.8-9.14)
后端·.net