Skip to content

Instantly share code, notes, and snippets.

@takamin
Last active August 29, 2015 13:56
Show Gist options
  • Save takamin/42b93386c73d0720fe79 to your computer and use it in GitHub Desktop.
Save takamin/42b93386c73d0720fe79 to your computer and use it in GitHub Desktop.
Avoids to fall into the deadlock in `Form.FormClose` when using `Invoke` by worker thread of the `Form` in DotNet 2.0.
public partial class MainForm : Form {
// Avoids dead lock problem when closed in invoking
private bool invoking = false;
private bool closeRequested = false;
public new object Invoke(Delegate program) {
object ret = null;
if (!closeRequested) {
invoking = true;
try {
ret = base.Invoke(program);
if (closeRequested) {
base.BeginInvoke((MethodInvoker)delegate { Close(); });
}
} catch (ObjectDisposedException) {
} finally {
invoking = false;
}
}
return ret;
}
private bool ShouldBeFormCloseDeferred() {
if (invoking) {
closeRequested = true;
return true;
}
return false;
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
if (ShouldBeFormCloseDeferred()) {
e.Cancel = true;
return;
}
// ...
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment