c# - 即使调度程序优先级设置为后台,在返回所有 UI 线程之前也无法关闭新的 WPF 窗口

标签 c# wpf multithreading

我是 WPF 新手,如果我做错了什么,我会一边做一边弥补。

我有一个主窗口,一旦特定的用户控件完成其业务,它就会创建一个新的“错误窗口”。这个新的错误窗口向 UI 返回一个“正在加载占位符”,同时后台线程正在更新“错误窗口”的另一部分。

        ErrorsWindow errorWindow = new ErrorsWindow();
        errorWindow.LoadingPlaceholder.Text = string.Format(@"Loading...
                                      Please wait {1} minutes and {0} seconds to see potential errors",
                                      ConfigurationManager.AppSettings["ErrorWindowWaitSeconds"],
                                      ConfigurationManager.AppSettings["ErrorWindowWaitMinutes"]);
        errorWindow.Show();
        this.Dispatcher.BeginInvoke((Action)(() =>
        {
            errorWindow.SetupWindow();
        }), System.Windows.Threading.DispatcherPriority.Background);

因此,我的 errorWindow 显示在 UI 中,并且加载占位符文本设置正确。然后,UI 等待 1 分 30 秒,让 errorWindow.SetupWindow() 方法完成。问题是,在此等待期间,我无法关闭窗口,直到 errorWindow.SetupWindow() 方法完成。 有没有办法让窗口关闭并中止后台线程?

编辑:我无法使用后台 worker 或任务,因为我需要更新 errorWindow.SetupWindow() 方法内的 UI 元素

谢谢你的期待

最佳答案

Dispatcher 上调用任何内容(如果 Dispatcher 属于 UI 线程)将仅在 UI 线程上运行您的委托(delegate)。因此,除非 UI 线程在其他地方忙碌,否则您无法关闭窗口。

设置优先级DispatcherPriority.Background不会使其在后台线程上运行。它设置了代表 DispatcherPriority背景。这意味着调度程序上优先级高于后台的所有排队委托(delegate)将在您的委托(delegate)有时间执行之前首先运行

如果您想在后台线程上运行操作,请使用 TaskBackgroundWorker .


根据 MSDN 的定义:

Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with.

如上所述,它在调度程序的关联线程上运行委托(delegate)。 (在您的情况下可能是 UI 线程)。

关于c# - 即使调度程序优先级设置为后台,在返回所有 UI 线程之前也无法关闭新的 WPF 窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173382/

相关文章:

c# - 如何在 C# 中将整数写入 FileStream?

wpf - 如何在WPF中为反斜杠键创建键绑定(bind)?

c# - WPF 中的网格表

c# - 无法使用 Caliburn Micro 绑定(bind)到 ToggleButton 的 IsEnabled 属性

java - 使用枚举类型创建的单例,线程安全问题

c# - 加入集合和列表在 C# Mongodb 强类型驱动程序中抛出 NotSupportedException

C# 在另一个函数中打破其他函数循环

c# - 如何使用 First Method 查询实体数据源的数据?

在单独的线程上运行的android服务

完成共同工作后取消 POSIX 线程