I have a splash screen for a WPF (using .net 4.5 and mvvmlight) that must perform various load operations in an async manner, showing progress and occasionally asking for user input.
When asking for input, I'll create forms/dialogs off the UI thread to call ShowDialog (with the splash screen as the parent) so that no cross-threading issues occur. This all works fine BUT if an error occurs when asking for input, the resulting exception is lost.
The examples below don't follow MVVM at all for simplicity.
Here is my app.cs, which set the UI dispatcher and is prepared to handle any unhandled dispatcher exceptions for error reporting:
public partial class App : Application
{
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
System.Windows.Forms.MessageBox.Show("Exception Handled");
}
private void Application_Startup(object sender, StartupEventArgs e)
{
GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize();
}
}
And here is my (very simplified) startup/splash screen:
private void Window_ContentRendered(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Starting long running process...");
var t = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
//some kind of threaded work which decided to ask for user input.
GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher.Invoke(() =>
{
//Show form for user input, launched on UIDispatcher so that it's created on the UI thread for ShowDialog etc
throw new Exception("issue in capturing input");
});
});
}
So I'm asking for user input through Invoke (because I want to wait for the answer) but even though I'm calling the work through the UIDispatcher, Application_DispatcherUnhandledException is never fired and the exception is lost. What am I missing? The example is using a Task for the threaded job but this also occurs when using BeginInvoke(). Surely the work (and resulting exception) should be occurring on the UIDispatcher?
UPDATE: Alternative demonstration (exception not handled) using BeginInvoke
private void Window_ContentRendered(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Starting long running process...");
Action anon = () =>
{
//some kind of threaded work which decided to ask for user input.
GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher.Invoke(() =>
{
//Show form for user input, launched on UIDispatcher so that it's created on the UI thread for ShowDialog etc
throw new Exception("issue in capturing input");
});
};
anon.BeginInvoke(RunCallback, null);
}
private void RunCallback(IAsyncResult result)
{
System.Windows.Forms.MessageBox.Show("Completed!");
}