I have a splash screen for WPF (using .net 4.5 and mvvmlight) that needs to perform various load operations in an asynchronous way, showing progress and occasionally requesting user input.
When prompted for input, I will create forms / dialogs from the user interface thread to call ShowDialog (with the splash screen as the parent) so that there are no problems with cross-threads. All this works fine, but if an error occurs while prompting for input, the resulting exception is lost.
The examples below are simply not consistent with MVVM for simplicity.
Here is my app.cs that installs the UI dispatcher and is ready 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 created on the UI thread for ShowDialog etc throw new Exception("issue in capturing input"); }); }); }
So, I ask to enter the user through Invoke (because I want to wait for an answer), but even if I call work through the UIDispatcher, Application_DispatcherUnhandledException is never raised and the exception is thrown. What am I missing? The example uses a task for a job with a stream, but this also happens when using BeginInvoke (). Surely the work (and the exception raised) should happen on UIDispatcher?
UPDATE: Alternative demo (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 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!"); }