diff --git a/TShockAPI/HandlerList.cs b/TShockAPI/HandlerList.cs index a258d99be..3222414e3 100644 --- a/TShockAPI/HandlerList.cs +++ b/TShockAPI/HandlerList.cs @@ -20,6 +20,7 @@ You should have received a copy of the GNU General Public License using System.Collections.Generic; using System.ComponentModel; using System.Linq; +using System.Threading; namespace TShockAPI { @@ -37,6 +38,7 @@ public class HandlerItem protected object HandlerLock = new object(); protected List Handlers { get; set; } + private HandlerItem[] _handlerSnapshot = Array.Empty(); public HandlerList() { Handlers = new List(); @@ -59,6 +61,7 @@ public void Register(HandlerItem obj) { Handlers.Add(obj); Handlers = Handlers.OrderBy(h => (int)h.Priority).ToList(); + Volatile.Write(ref _handlerSnapshot, Handlers.ToArray()); } } @@ -66,21 +69,21 @@ public void UnRegister(EventHandler handler) { lock (HandlerLock) { - Handlers.RemoveAll(h => h.Handler.Equals(handler)); + if (Handlers.RemoveAll(h => h.Handler.Equals(handler)) > 0) + { + Volatile.Write(ref _handlerSnapshot, Handlers.ToArray()); + } } } public void Invoke(object sender, T e) { - List handlers; - lock (HandlerLock) - { - //Copy the list for invoking as to not keep it locked during the invokes - handlers = new List(Handlers); - } + var handlers = Volatile.Read(ref _handlerSnapshot); + if (handlers.Length == 0) + return; var hargs = e as HandledEventArgs; - for (int i = 0; i < handlers.Count; i++) + for (int i = 0; i < handlers.Length; i++) { if (hargs == null || !hargs.Handled || (hargs.Handled && handlers[i].GetHandled)) {