Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show MessageBox from thread as it were from the main thread in C#/WPF

There is a thread which can throw an exception, and when does so it is caught, a certain message box is shown, and then the software closes.

However, the problem is that since it is not the program's main thread, when I show the message box, the program window remains free for the user to interact with. It does not lock the screen, unlike when the message box is shown above the main window. I want to avoid this.

I wanted to know what would be the best way to do this. Up to now, I thought of using some kind of thread communication (never used this in C#) to raise the message box from the main thread.

Raising the thread:

Thread thread = new Thread(new ThreadStart(MyClass.MyMethod));
thread.IsBackground = true;
thread.Start();

The capture of the exception is in various parts of MyMethod. It is a thread that keeps running nonstop in a loop since the start of the program. The cause of the exception would be a network error.

like image 216
André Santaló Avatar asked Dec 16 '22 04:12

André Santaló


1 Answers

You can probably just invoke it on the Dispatcher:

Application.Current.Dispatcher.Invoke(() => MessageBox.Show(...));
like image 104
Mike Perrenoud Avatar answered Dec 22 '22 00:12

Mike Perrenoud