且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用.NET 4任务库在WPF中显示阻止消息框

更新时间:2023-01-25 15:23:14

通常,通常是通过适当的 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.