add locking to BroadcasterService

This commit is contained in:
Kyle Spearrin 2019-06-04 21:28:50 -04:00
parent f6f6253eab
commit 6c88d25941

View file

@ -9,8 +9,11 @@ namespace Bit.App.Services
public class BroadcasterService : IBroadcasterService public class BroadcasterService : IBroadcasterService
{ {
private readonly Dictionary<string, Action<Message>> _subscribers = new Dictionary<string, Action<Message>>(); private readonly Dictionary<string, Action<Message>> _subscribers = new Dictionary<string, Action<Message>>();
private object _myLock = new object();
public void Send(Message message, string id = null) public void Send(Message message, string id = null)
{
lock(_myLock)
{ {
if(!string.IsNullOrWhiteSpace(id)) if(!string.IsNullOrWhiteSpace(id))
{ {
@ -25,8 +28,11 @@ namespace Bit.App.Services
Task.Run(() => sub.Value.Invoke(message)); Task.Run(() => sub.Value.Invoke(message));
} }
} }
}
public void Subscribe(string id, Action<Message> messageCallback) public void Subscribe(string id, Action<Message> messageCallback)
{
lock(_myLock)
{ {
if(_subscribers.ContainsKey(id)) if(_subscribers.ContainsKey(id))
{ {
@ -34,8 +40,11 @@ namespace Bit.App.Services
} }
_subscribers.Add(id, messageCallback); _subscribers.Add(id, messageCallback);
} }
}
public void Unsubscribe(string id) public void Unsubscribe(string id)
{
lock(_myLock)
{ {
if(_subscribers.ContainsKey(id)) if(_subscribers.ContainsKey(id))
{ {
@ -43,4 +52,5 @@ namespace Bit.App.Services
} }
} }
} }
}
} }