.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 小时前
66.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--自动记账
微服务·架构·.net
故事不长丨20 小时前
C#log4net详解:从入门到精通,配置、实战与框架对比
c#·.net·wpf·log4net·日志·winform·日志系统
bjzhang751 天前
OneAuthCenter——一款基于 .NET打造的企业级 OAuth 2.0 / OpenID Connect 认证中心
.net·认证中心
步步为营DotNet1 天前
深度解析.NET 中Nullable<T>:灵活处理可能为空值的类型
java·前端·.net
csdn_aspnet1 天前
.NET 10 中的 ASP.NET Core:Blazor、API 和 OpenAPI 的重大更新
后端·asp.net·.net·.net10
weixin_421994782 天前
认识数据 - 变量与数据类型
c#·.net·.netcore
mudtools2 天前
深入理解飞书 Webhook 签名验证:一次踩坑到填坑的完整记录
网络·c#·.net·飞书
工业甲酰苯胺2 天前
如何一步步将 ASP.NET MVC 升级为.NET
asp.net·mvc·.net
闻缺陷则喜何志丹2 天前
【.NetAPI]统计标注的值、上公差、下公差
数学·.net·cad·netapi
一念一花一世界2 天前
Arbess项目实战 - 基于GitLab搭建.net项目自动化流水线
ci/cd·gitlab·.net·arbess