Using the .NET 4 task library to display a block of blocking messages in WPF

I have the following code in my WPF application:

Task task = Task.Factory.StartNew(() => { DoInitialProcess(); }); task.ContinueWith(t => Dispatcher.BeginInvoke((Action)(() => { MessageBox.Show("Error: " + t.Exception.InnerExceptions[0].Message); })), TaskContinuationOptions.OnlyOnFaulted); 

It successfully starts the continuation and displays a message box if an exception occurs, but it does not block input in the main user interface thread.

Why doesn't it block the main UI thread, and what is the best way to do this?

+4
source share
1 answer

In general, the way this is usually done is through the TaskScheduler , and not through Dispatcher.BeginInvoke . Try the following:

 task.ContinueWith(t => { MessageBox.Show("Error: " + t.Exception.InnerExceptions[0].Message); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); 

If you create this task in a user interface thread, the above should work as you expect.

If, however, you run this task in the background thread, you need to provide a clean way to get the correct TaskScheduler to continue. This can be done by capturing the scheduler while building a window or other tools, and then using it later.

+5
source

Source: https://habr.com/ru/post/1391921/


All Articles