Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions TShockAPI/HandlerList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -37,6 +38,7 @@ public class HandlerItem

protected object HandlerLock = new object();
protected List<HandlerItem> Handlers { get; set; }
private HandlerItem[] _handlerSnapshot = Array.Empty<HandlerItem>();
public HandlerList()
{
Handlers = new List<HandlerItem>();
Expand All @@ -59,28 +61,29 @@ public void Register(HandlerItem obj)
{
Handlers.Add(obj);
Handlers = Handlers.OrderBy(h => (int)h.Priority).ToList();
Volatile.Write(ref _handlerSnapshot, Handlers.ToArray());
}
}

public void UnRegister(EventHandler<T> 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<HandlerItem> handlers;
lock (HandlerLock)
{
//Copy the list for invoking as to not keep it locked during the invokes
handlers = new List<HandlerItem>(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))
{
Expand Down