I would like to remoe duplicate delegates from an event. So I have written the following code. It works fine. My application is a time critcal application. Is there any other optimized mechansim to achieve the same. Please help me
public void FireEvent()
{
Dictionary<Delegate, Delegate> dic = new Dictionary<Delegate, Delegate>();
Delegate[] m = this.Paused.GetInvocationList();
foreach (Delegate d in m)
{
Delegate dout;
if (dic.TryGetValue(d, out dout))
{
continue;
}
else
{
dic.Add(d, d);
}
d.DynamicInvoke(new object[2] { this, null });
}
}
Problem with original approach
If this is really a time critical application, I would strongly advise changing your code.
Dictionary<Delegate, Delegate>on every method call. This is quite wasteful.DynamicInvoke, which has slower performance than regular invocation to begin with.object[]to pass as a parameter to yourDynamicInvokecall, again on everyFireEventcall.This is a bit of a corruption of the established mechanism for event handling.
Suggestion for improved approach
Here’s a much better solution, in my opinion: instead of having this
FireEventmethod which bends over backwards to ignore duplicate delegates that have been added, why not just prevent delegates from being attached to the event multiple times in the first place?Then you can simply raise the event in the much more conventional, time-tested way, confident that no delegates have been attached to the event more than once.
Note on the concept of “duplicate delegates”
The comments to this answer have shed some light on the issue of delegate equality that I felt it would be beneficial to include in this answer. If you’re interested, take a look at the following code example I wrote in an attempt to make this topic a little bit easier to understand.