Running an issue with multi-threading and WPF. I don't really know what I'm doing and the usual stackoverflow answers aren't working out.
First off, a bunch of WPF windows are created via:
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();
In the ctor of the spawned windows, a viewmodel is created and an event is listened to where the viewmodel should be changed.
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);
});
The viewmodel state is modified like this:
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");
});
}
Problem is accessing Application.Current.Dispatcher
results in a NullReferenceException
. Is there something wrong with the way the windows are spawned?