Make event listeners thread safe

This commit is contained in:
Frank A. Krueger 2017-06-15 17:50:57 -07:00
parent 2729418006
commit 096c42adbc
1 changed files with 21 additions and 12 deletions

View File

@ -51,12 +51,14 @@ namespace Ooui
var sendListen = false;
List<EventHandler> handlers;
lock (eventListeners) {
if (!eventListeners.TryGetValue (eventType, out handlers)) {
handlers = new List<EventHandler> ();
eventListeners[eventType] = handlers;
sendListen = true;
}
handlers.Add (handler);
}
if (sendListen)
Send (new Message {
@ -72,10 +74,12 @@ namespace Ooui
if (handler == null) return;
List<EventHandler> handlers;
lock (eventListeners) {
if (eventListeners.TryGetValue (eventType, out handlers)) {
handlers.Remove (handler);
}
}
}
protected bool SetProperty<T> (ref T backingStore, T newValue, string attributeName, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
@ -169,15 +173,20 @@ namespace Ooui
protected virtual void TriggerEventFromMessage (Message message)
{
List<EventHandler> handlers;
if (eventListeners.TryGetValue (message.Key, out handlers)) {
List<EventHandler> handlers = null;
lock (eventListeners) {
List<EventHandler> hs;
if (eventListeners.TryGetValue (message.Key, out hs)) {
handlers = new List<EventHandler> (hs);
}
}
if (handlers == null) return;
var args = EventArgs.Empty;
foreach (var h in handlers) {
h.Invoke (this, args);
}
}
}
}
class EventTargetJsonConverter : Newtonsoft.Json.JsonConverter
{