本文介绍了使用.NET 4任务库在WPF中显示阻止消息框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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);

如果发生异常,它将成功触发继续并显示消息框,但是它不会阻止主UI线程上的输入.

It successfully triggers the continuation and displays the message box if an exception occurs, but it does not block input on the main UI thread.

为什么它不阻塞主UI线程,什么才是最好的方法?

Why doesn't it block the main UI thread, and what is the best approach to make it do so?

推荐答案

通常,通常是通过适当的 TaskScheduler 而不是通过 Dispatcher.BeginInvoke .请尝试以下操作:

In general, the way this would typically be done is via a proper TaskScheduler, not via Dispatcher.BeginInvoke. Try the following:

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

假设您正在UI线程中创建此任务,则上面的操作应按您期望的方式进行.

Provided you're creating this task in the UI thread, the above should work the way you expect.

但是,如果要在后台线程上启动此任务,则需要提供一种干净的方法来使正确的 TaskScheduler 延续.这可以通过在构造窗口或其他方式时抓住调度程序,然后在以后使用来完成.

If, however, you're starting this task on a background thread, you'll need to provide a clean way to get the proper TaskScheduler to the continuation. This can be done by grabbing the scheduler during a window's construction or some other means, and then using it later.

这篇关于使用.NET 4任务库在WPF中显示阻止消息框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:38