Safe to Remove Now?
private void button1_Click(object sender, System.EventArgs e)
{
DoItOnce();
button1.Click-=new EventHandler(button1_Click);
}
If you think about it for a second, the above code is a little trickier than it appears at first. Something somewhere is traversing an array of delegates and invoking each one. The invocation of this particular delegate removes the delegate from the array. Removing items from arrays that you are currently iterating through can, if handled carelessly, cause problems, no? Nonetheless, if MS had been so careless in coding the framework as to give rise to those sorts of problems, you wouldn’t trust them to .. I dunno.. collect your garbage much less any of the fancy computer stuff you count on the them for.
So with that faith in heart you come to Application.AddMessageFilter. This method allows you supposedly to get a crack at all messages posted to your app’s message loop. ( I say supposedly because all I’ve ever seemed to be able to get out of it are keyboard and mouseevents. But maybe that’s just me.) Whatever it is doing it must be working somewhat like the event sink: it’s going through the list of registered PreFilterMessage delegates and calling them. But what if you do this:
public bool PreFilterMessage(ref Message msg)
{
if(_quit)
Application.RemoveMessageFilter(this);
return false;
}
The answer is that if you’ve got any other IMessageFilter’s listening to this app, you’re dead, with the epitaph:
An unhandled exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
Very disappointing.



March 27th, 2006 at 9:56 pm
Haven’t you learnt by now that Bill Gates and Co do the least amount of work possible for the greatest financial return, even if that causes programmers endless frustration on a daily basis. I learnt many years ago to never saw off the branch on which I’m sitting, ie don’t delete from a collection you are traversing or at least work backwards if its ordered.