【问题标题】:WPF UI thread does not resume after modal dialog is closed - Intermittent模式对话框关闭后 WPF UI 线程不会恢复 - 间歇性
【发布时间】:2022-12-19 23:29:02
【问题描述】:

在我的 WPF 应用程序中,我在 Task 下处理一些操作,如下所示:

// This gets called on a button click
public void ProcessButton()
{
    ProcessTask(() => 
    {
        // Some code here
    });

    // Code below this does not executes sometime.
    DoSomeOtherWork();
}

private void ProcessTask(Action action)
{
    var task = Task.Factory.StartNew(action);
    task.ContinueWith(r =>
    {
        myModal.Close(); // The modal always gets closed
        // Any code here always executes
    },
    TaskScheduler.FromCurrentSynchronizationContext());

    // Show the modal dialog which blocks the UI thread
    myModal.ShowDialog();
}

对于大多数情况,DoSomeOtherWork 方法在模式关闭后执行。但是有时,它不会。没有发生错误/异常。此行为仅在生产中观察到。

这个应用程序中还有许多其他后台操作在运行,所以我不确定是否有任何干扰。该应用程序是在 .NET Framework 4.6 中构建的

【问题讨论】:

  • 你总是创建一个新的 myModal 对象吗? ShowDialog 只能为一个窗口对象调用一次。
  • 是的,我总是创建一个新的 myModal 然后关闭,处理它
  • TaskScheduler.FromCurrentSynchronizationContext());一个额外的)?
  • 可能会发生错误/异常,但您永远不会await您的Task。您也没有检查是否完成或任何附加的异常。所以抛出的任何异常都不会显示。
  • @HSharma:当它被阻塞等待对话框关闭时,应该如何在 UI 线程上执行任务的继续......?

标签: c# .net wpf multithreading task-parallel-library


【解决方案1】:

在等待对话框关闭时,无法在 UI 线程上执行继续操作。您的代码将死锁。

删除TaskScheduler.FromCurrentSynchronizationContext()在后台线程上执行继续操作,然后使用调度程序关闭对话框:

private void ProcessTask(Action action)
{
    var task = Task.Factory.StartNew(action);
    task.ContinueWith(r =>
    {
        myModal.Dispatcher.BeginInvoke((Action)(() => myModal.Close()));
    });

    // Show the modal dialog which blocks the UI thread
    myModal.ShowDialog();
}

您可能还想处理 action 抛出的任何异常,但这是另一回事了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多