.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#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
2501_930707782 天前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
向上的车轮2 天前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
波波0072 天前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
波波0073 天前
每日一题:中间件是如何工作的?
中间件·.net·面试题
无风听海3 天前
.NET 10之可空引用类型
数据结构·.net
码云数智-园园3 天前
基于 JSON 配置的 .NET 桌面应用自动更新实现指南
.net
无风听海3 天前
.NET 10 之dotnet run的功能
.net
岩屿3 天前
Ubuntu下安装Docker并部署.NET API(二)
运维·docker·容器·.net
码云数智-大飞3 天前
.NET 中高效实现 List 集合去重的多种方法详解
.net