I was recently asked a question what will happen if I would query one handler twice. Let me just show you code:
public delegate void OpenEventHandler(object sender, EventArgs e);
public class MyWindow
{
public event OpenEventHandler Open;
public void OpenWindow()
{
if (Open != null)
{
Open(this, new EventArgs());
}
}
}
public class TwoDelegates
{
public static void HandleOpen(Object sender, EventArgs e)
{
Console.WriteLine("Birds fly");
(sender as MyWindow).Open -= HandleOpen;
}
public static void Run()
{
var window = new MyWindow();
window.Open += HandleOpen;
window.Open += HandleOpen;
window.OpenWindow();
Console.ReadKey();
}
}
I wonder why string is still printed twice. On the beginning of it Invocation list consist of two items with same delegate reference, but after a first run it is cleaned up, still the secon invocaiton appears.
Update1:
Seems that even simple -=
removes only one entry:
var window = new MyWindow();
window.Open += HandleOpen;
window.Open += HandleOpen;
Console.WriteLine(window.getHandlers().Count());
window.Open -= HandleOpen;
Console.WriteLine(window.getHandlers().Count());
Though debug mode in VS2010, while you look through window.Open
internal properties shows empty invocation list with 0 count. Seems that it's some magic in debug info displayed in VS.