gpt4 book ai didi

c# - 在静态方法中正确锁定变量

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:38 25 4
gpt4 key购买 nike

我正在使用 SignalR 通知客户一些变化。我的集线器(但知道它是 SignalR 集线器并不重要)定义为

public class NotificationHub : Hub
{
private static readonly IHubContext HubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

private static readonly IDictionary<int, string> UserConnectionMapping = new Dictionary<int, string>();

private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

private const string UserId = "UserId";

private readonly object userConnectionMappingLock = new object();



public static void Static_UpdateStatus(int userId, string message)
{
lock(userConnectionMappingLock ) //This causes troubles
{
if (UserConnectionMapping.ContainsKey(userId))
{
var connectionId = UserConnectionMapping[userId];

HubContext.Clients.Client(connectionId).updateNotifications(message);
}
}
}
public override Task OnConnected()
{
if (Context.QueryString[UserId] == null) return base.OnConnected();

var userId = int.Parse(Context.QueryString[UserId]);
Log.Debug($"User {userId} connected on SignalR with Connection Id {Context.ConnectionId}");

lock (userConnectionMappingLock)
{
UserConnectionMapping[userId] = Context.ConnectionId;
}

return base.OnConnected();
}

既然方法是静态的(因为我需要从外部类访问,所以它不能是静态的),我是否也应该将锁声明为静态的?假设只有 1 个 NotifyHub 实例。谢谢

最佳答案

你锁定的东西和被保护的东西应该有相同的生命周期和范围;此刻UserConnectionMappingstatic , 和 userConnectionMappingLock是针对每个实例的,这是灾难的根源。

坦率地说,static字典总是有点危险,但它们可以安全地使用;选项:

  1. 制作userConnectionMappingLock匹配字典的范围 - 添加 staticuserConnectionMappingLock (或从 static 中删除 UserConnectionMapping,参见 3)
  2. 失去userConnectionMappingLock 完全(把它扔掉)和lock 字典本身 ( UserConnectionMapping )
  3. 制作UserConnectionMapping 不是 static - 所以每个集线器实例都有一个字典(假设 NotificationHub 的生命周期适用)
  4. 使用ConcurrentDictrionary<int,string>

我可能会倾向于最后一个 - 你不太可能用它来射你的脚。尽管我认为除了 1/2/4 中的任何一个之外,还可以应用 3 个

关于c# - 在静态方法中正确锁定变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com