C# WPF:从Dispatcher修改CollectionView仍会引发错误
我有下面一段代码,每当用户离开时,它会修改一个可观察的“屏幕”集合C# WPF:从Dispatcher修改CollectionView仍会引发错误,c#,wpf,dispatcher,C#,Wpf,Dispatcher,我有下面一段代码,每当用户离开时,它会修改一个可观察的“屏幕”集合 void OnUserLeft(int roomId, int userId, string username) { client.ClientDispatcher.Invoke( (Action<int>)((id) => { Console.WriteLine("Hello before the sto
void OnUserLeft(int roomId, int userId, string username)
{
client.ClientDispatcher.Invoke(
(Action<int>)((id) =>
{
Console.WriteLine("Hello before the storm!");
var screensToCheck = client.Screens.Where(s => s.CpuId == id).ToList();
screensToCheck.Each(s => client.Screens.Remove(s));
Console.WriteLine("Hello there!");
}), userId);
}
根据以下文件:
获取当前正在执行的线程的调度程序,如果尚未与该线程关联,则创建新的调度程序
看起来您正在访问CurrentDispatcher
,而不是在UI线程中,并调用对其的操作(即,调用根本没有效果,因为您所在的线程中没有Dispatcher;此时会创建一个新的Dispatcher,调用会转到它)
您应该在创建客户端
实例的位置保存Dispatcher.CurrentDispatcher
的值(假设您是从UI线程中执行此操作),例如:
class Client {
Client() {
this.OwningDispatcher = Dispatcher.CurrentDispatcher;
}
Dispatcher OwningDispatcher { get; private set; }
}
如果您的
客户端
实例未在UI线程上创建,您需要某种方法将Dispatcher
的正确值传递给它们。什么是“客户端的Dispatcher”?抱歉,在问题中添加了一点关于“ClientDispatcher”的内容。这是我们第一次尝试删除某些内容,使用Dispatcher执行此操作。你是说我们的调度器一开始可能没有正确实现?我现在就试试。成功!先生,你很聪明。我不会把这称为聪明的结果。我只是仔细阅读了代码使用的特性的文档。:-)
class Client {
Client() {
this.OwningDispatcher = Dispatcher.CurrentDispatcher;
}
Dispatcher OwningDispatcher { get; private set; }
}