I have a real world need for what I'm going to ask, but to make it simple I've boiled the issue down to this.
- Create a C# windows forms application project
- Add a textbox and a button to the form.
- Add a Leave event to the textbox.
- Add a Click event to the button.
With this code
private void textBox1_Leave(object sender, EventArgs e) {
button1.Dispose();
}
private void button1_Click(object sender, EventArgs e) {
MessageBox.Show("in button 1");
}
Run the project and put your cursor in the textbox. Now leave by clicking on the button.
By leaving the textbox you cause the button to be Disposed, but the Click event for the button is sitting behind the textbox's Leave event waiting to be handled. But there's no textbox anymore so you get the ObjectDisposedException.
So,.... the question is how do I eliminate the queued event so I can safely Dispose of the button.