【发布时间】:2018-05-17 12:01:27
【问题描述】:
我正在尝试关闭我在与主宿主线程不同的线程中创建的 WPF 窗口(主线程是我无法控制的 PDM 应用程序)。主机应用程序引用了我的程序集(它是一个插件)。 我不知道为什么 Dispatcher 总是为空。在主机应用程序上创建 WaitView 对我来说不是一个选项。
谢谢大家!
var WaitViewModel = new MVVM.ViewModels.WaitViewModel();
MVVM.Views.WaitView WaitView = default(MVVM.Views.WaitView);
Dispatcher dispatcher = default(Dispatcher);
var thread = new Thread(new ThreadStart(() =>
{
dispatcher = Dispatcher.CurrentDispatcher;
WaitView = new MVVM.Views.WaitView();
WaitView.Topmost = true;
WaitView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
WaitView.DataContext = WaitViewModel;
WaitView.Show();
System.Windows.Threading.Dispatcher.Run();
}));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
'unrelated code here
if (dispatcher != null)
dispatcher.Invoke(()=>
{
WaitView.Close();
});
【问题讨论】:
-
您不能在非 UI 线程中创建 UI 元素。
-
@Enigmativity 你介意解释一下原因吗?
-
UI 元素不是线程安全的,因此任何交叉调用都可能破坏 UI 状态。调度程序和消息泵之类的设置不正确。
标签: c# multithreading dispatcher