In C # or .NET, is there a way to prevent other threads from using methods in a specific thread?

I have a Windows Forms application with BackgroundWorker. The MessageBox is displayed in the main form method, and the user must click OK to continue. Meanwhile, while the message is displayed, BackgroundWorker completes the execution and raises the RunWorkerCompleted event. In the method that I assigned to this event, which is executed in the user interface thread, the Close method is called on the form. Although the method that displays the message box still works, the UI thread does not block other threads from calling methods on it. Therefore, the Close method is called on the form. I want the UI thread to block calls to other threads until the message method completes. Is there an easy way to do this?

+4
source share
3 answers

I think you should be more disciplined about how your events are handled. You do not want to stop the methods called in the user interface thread, because the method invocation mechanism is the same as the one that allows you to work like mouse and keyboard events. If you block a method call, you will also block it. Instead, you need to somehow delay the methods. To do this, you may need to write your own synchronization code.

+1
source

Use ManualResetEvent to control the timing between the RunWorkCompleted event and the MessageBox display method.

0
source

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; } 
0
source

Source: https://habr.com/ru/post/1308494/


All Articles