To do this, you can use a simple lock . In your form, create an element at the form level as follows:
private object _locker = new object();
Then your code will get a lock in both methods, for example:
private void RunWorkerCompleted() { lock (_locker) { this.Close(); } } private void ShowSomeMessage() { lock (_locker) { MessageBox.Show("message"); } }
If your code is currently blocked in ShowSomeMessage() (i.e. the message window is still open), the RunWorkerCompleted() method will wait until the message window is closed (release the lock) before closing the form.
Update: this should work no matter which thread causes what:
private bool _showingMessage = false;
Then your code will get a lock in both methods, for example:
private void RunWorkerCompleted() { while (_showingMessage) { Thread.Sleep(500); // or some other interval (in ms) } this.Close(); } private void ShowSomeMessage() { _showingMessage = true; MessageBox.Show("message"); _showingMessage = false; }
source share