From 6c88d25941190771444310262e132d71b4bb57de Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Tue, 4 Jun 2019 21:28:50 -0400 Subject: [PATCH] add locking to BroadcasterService --- src/Core/Services/BroadcasterService.cs | 36 ++++++++++++++++--------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/src/Core/Services/BroadcasterService.cs b/src/Core/Services/BroadcasterService.cs index a19bfaa79..2dec85b80 100644 --- a/src/Core/Services/BroadcasterService.cs +++ b/src/Core/Services/BroadcasterService.cs @@ -9,37 +9,47 @@ namespace Bit.App.Services public class BroadcasterService : IBroadcasterService { private readonly Dictionary> _subscribers = new Dictionary>(); + private object _myLock = new object(); public void Send(Message message, string id = null) { - if(!string.IsNullOrWhiteSpace(id)) + lock(_myLock) { - if(_subscribers.ContainsKey(id)) + if(!string.IsNullOrWhiteSpace(id)) { - Task.Run(() => _subscribers[id].Invoke(message)); + if(_subscribers.ContainsKey(id)) + { + Task.Run(() => _subscribers[id].Invoke(message)); + } + return; + } + foreach(var sub in _subscribers) + { + Task.Run(() => sub.Value.Invoke(message)); } - return; - } - foreach(var sub in _subscribers) - { - Task.Run(() => sub.Value.Invoke(message)); } } public void Subscribe(string id, Action messageCallback) { - if(_subscribers.ContainsKey(id)) + lock(_myLock) { - return; + if(_subscribers.ContainsKey(id)) + { + return; + } + _subscribers.Add(id, messageCallback); } - _subscribers.Add(id, messageCallback); } public void Unsubscribe(string id) { - if(_subscribers.ContainsKey(id)) + lock(_myLock) { - _subscribers.Remove(id); + if(_subscribers.ContainsKey(id)) + { + _subscribers.Remove(id); + } } } }