I'm using SignalR to notify clients about some changes. My hub (but it's not fundamental to know it's a SignalR hub) is defined as
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();
}
Since it's static the method (and it can't be otherwise since I need to access from external classes), should I declare the lock static as well? Consider that there will be only 1 instance of NotifyHub. Thanks