The problem with the original approach
If this is a really time-critical application, I would highly recommend changing your code.
- You create and populate a new one
Dictionary<Delegate, Delegate>each time you call a method. This is pretty wasteful. - You use
DynamicInvokeone that has lower performance than a normal call to start with. object[] DynamicInvoke FireEvent.
.
, : , FireEvent, , , , ?
private HashSet<EventHandler> _pausedHandlers = new HashSet<EventHandler>();
public event EventHandler Paused
{
add
{ _pausedHandlers.Add(value); }
remove
{ _pausedHandlers.Remove(value); }
}
, , , .
protected void OnPaused()
{
foreach (EventHandler handler in _pausedHandlers)
{
try
{
handler(this, EventArgs.Empty);
}
catch
{
}
}
}
" "
, , , . , , , .
class Program
{
static void Main(string[] args)
{
EventHandler handler1 = FirstHandler;
EventHandler handler2 = SecondHandler;
EventHandler handler3 = SecondHandler;
Console.WriteLine(handler1.Equals(handler2));
Console.WriteLine(handler2.Equals(handler3));
Console.WriteLine(SetAnonymousHandler(ref handler1));
Console.WriteLine(SetAnonymousHandler(ref handler1));
Console.ReadLine();
}
static void FirstHandler(object sender, EventArgs e)
{
Console.WriteLine("Testing");
}
static void SecondHandler(object sender, EventArgs e)
{
Console.WriteLine("Testing");
}
static bool SetAnonymousHandler(ref EventHandler handler)
{
EventHandler anonymous = (sender, e) => Console.WriteLine("Testing");
if (!handler.Equals(anonymous))
{
handler = anonymous;
return true;
}
else
{
return false;
}
}
}