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; var sendListen = false;
List<EventHandler> handlers; List<EventHandler> handlers;
if (!eventListeners.TryGetValue (eventType, out handlers)) { lock (eventListeners) {
handlers = new List<EventHandler> (); if (!eventListeners.TryGetValue (eventType, out handlers)) {
eventListeners[eventType] = handlers; handlers = new List<EventHandler> ();
sendListen = true; eventListeners[eventType] = handlers;
sendListen = true;
}
handlers.Add (handler);
} }
handlers.Add (handler);
if (sendListen) if (sendListen)
Send (new Message { Send (new Message {
@ -72,8 +74,10 @@ namespace Ooui
if (handler == null) return; if (handler == null) return;
List<EventHandler> handlers; List<EventHandler> handlers;
if (eventListeners.TryGetValue (eventType, out handlers)) { lock (eventListeners) {
handlers.Remove (handler); if (eventListeners.TryGetValue (eventType, out handlers)) {
handlers.Remove (handler);
}
} }
} }
@ -169,13 +173,18 @@ namespace Ooui
protected virtual void TriggerEventFromMessage (Message message) protected virtual void TriggerEventFromMessage (Message message)
{ {
List<EventHandler> handlers; List<EventHandler> handlers = null;
if (eventListeners.TryGetValue (message.Key, out handlers)) { lock (eventListeners) {
var args = EventArgs.Empty; List<EventHandler> hs;
foreach (var h in handlers) { if (eventListeners.TryGetValue (message.Key, out hs)) {
h.Invoke (this, args); handlers = new List<EventHandler> (hs);
} }
} }
if (handlers == null) return;
var args = EventArgs.Empty;
foreach (var h in handlers) {
h.Invoke (this, args);
}
} }
} }