Last active
August 29, 2015 13:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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