I am running some code in a separate thread, which might throw an exception (after all, code tends to do this). The thread will be spawned from the main thread (GUI) so this is where the exceptions will eventually have to be handled (like setting an error message text block). I have two solutions, but neither allows direct catching of exceptions in the GUI thread.
Note: I cannot use stuff like Task
and BackgroundWorker
(at least not out of the box) as I need to be able to change the ApartmentState
of the thread.
Here is what I would like:
var thread = new Thread(() =>
{
// Code which can throw exceptions
});
try
{
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
MethodThatAwaitsThread(thread);
}
catch
{
// Exception handling in the GUI thread
}
This does not work, as the exception never leaves the thread. I am aware that it cannot leave the thread at any time, but I am fine with waiting for the thread to end, and then catch it.
Here is my current solution, which utilizes the Dispatcher
to talk to the GUI thread:
var thread = new Thread(() =>
{
try
{
// Code which can throw exceptions
Dispatcher.Invoke(UpdateGuiAsSuccess);
}
catch (Exception ex)
{
Dispatcher.Invoke(UpdateGuiAsError);
}
}
An alternative solution is to store the Exception
in an object and then explicitely check for it afterwards. But this comes at a risk of people forgetting to check the exception:
Exception ex = null;
var thread = new Thread(() =>
{
try
{
// Code which can throw exceptions
}
catch (Exception threadEx)
{
ex = threadEx;
}
}
if (ex != null)
{
UpdateGuiAsError();
}
else
{
UpdateGuiAsSuccess();
}
Is there anyway I can get the error to be re-thrown in the GUI thread, once the worker thread dies?