【发布时间】:2021-10-17 19:14:39
【问题描述】:
使用多线程和 WPF 运行问题。我真的不知道自己在做什么,而且通常的 stackoverflow 答案也不起作用。
首先,通过以下方式创建了一堆 WPF 窗口:
var thread = new Thread(() =>
{
var bar = new MainWindow(command.Monitor, _workspaceService, _bus);
bar.Show();
System.Windows.Threading.Dispatcher.Run();
});
thread.Name = "Bar";
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
在生成的窗口的 ctor 中,创建了一个视图模型,并在应该更改视图模型的位置监听一个事件。
this.DataContext = new BarViewModel();
// Listen to an event propagated on main thread.
_bus.Events.Where(@event => @event is WorkspaceAttachedEvent).Subscribe(observer =>
{
// Refresh contents of viewmodel.
(this.DataContext as BarViewModel).SetWorkspaces(monitor.Children);
});
视图模型状态修改如下:
public void SetWorkspaces(IEnumerable<Workspace> workspaces)
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
this.Workspaces.Clear(); // this.Workspaces is an `ObservableCollection<Workspace>`
foreach (var workspace in workspaces)
this.Workspaces.Add(workspace);
this.OnPropertyChanged("Workspaces");
});
}
问题是访问Application.Current.Dispatcher 导致NullReferenceException。生成窗口的方式有问题吗?
【问题讨论】:
-
我真的不知道我在做什么 -> 你为什么选择在一个单独的线程中构建窗口?所有 UI 工作都应在 UI 线程上完成。
-
该应用程序的其余部分是一个标准的 .NET 核心控制台应用程序,我需要一种以编程方式生成 WPF 窗口的方法。我有一个业务逻辑所在的主线程,所以我这样做只是因为它似乎完成了打开窗口的工作。有没有更好的方法来生成窗口?
标签: c# wpf multithreading