Canceling Dialog

As I made review of one application I got reminded of one common error. Theory of cancel button is easy enough. It is enough to set button's DialogResult to Cancel and form's CancelButton property to that button and form will close automatically. However, what to do if we need to cancel some background operation?

More than once I saw cancel code inside of cancel button's Click event. This is WRONG. If you are wondering why, just take a look at your application state when somebody decides to close dialog via small red button in upper right corner instead of pressing cancel button. All that carefully crafted cancel code never gets chance to execute.

Solution is trivial. All your code should go inside of either FormClosing or FormClosed event. These events get triggered whatever way you do form cancelling:

    private void Form_FormClosed(object sender, FormClosedEventArgs e) {
if (backgroundWorker.IsBusy) { backgroundWorker.CancelAsync(); } //just an example of cancellation code
}

Cancel button should NEVER have any code in it.

P.S. Whether to use FormClosing or FormClosed is mostly matter of philosophical discussion that I intend to leave for other post.

Leave a Reply

Your email address will not be published. Required fields are marked *