edit:
error I got is unrelated to my question. :/
-1
I starting a service on a new thread, then I want to catch an error and display a message box. because its not in the UI thread I get an error. How can I get arround this problem?
(WPF window)
Code:
xmlServiceHost = XcelsiusServiceHost.CreateXmlServiceHost(Properties.Settings.Default.XmlDataService);
serviceThread = new Thread(_ =>
{
try { xmlServiceHost.Open(); }
catch (AddressAccessDeniedException)
{
CreateRegisterDashboardServiceFile();
//Error not in UI thread.
//this.ShowUserInfoMessage("The dashboard service needs to be registered. Please contact support.");
}
});
serviceThread.Start();
(This answer is for WPF.)
Well, you can open a message box from – lets say – a worker thread, but you cannot set its parent to something that belongs to the UI thread (because the worker thread would be changing the parent window by adding a new child, and the parent window does not belong to the worker thread, it normally belongs to the UI thread), so you are basically forced to leave the parent null.
This will lead to a bunch of message boxes lying behind your application window if users don’t close them but reactivate the application window.
What you should do is to create the message box on the UI thread with the proper parent window. For that you will need the dispatcher for the UI thread. The dispatcher will open your message box on the UI thread and you can set its proper parent.
In situations like that I normally pass the UI dispatcher into the worker thread when I start the thread and then use a little helper class, this is particularly useful for handling exceptions on the worker thread: