Skip to main content
 首页 » 编程设计

c#之async/await 更改后,使用 Dispatcher.Invoke() 不能解决除 Dispatcher 线程以外的 CollectionView 更改

2024年02月13日13mengfanrong

我对我的应用程序进行了更改,以便在应用程序打开时在后台线程上加载数据(使用异步/等待)。现在,在应用程序完全加载后,当尝试更新绑定(bind)属性时,出现此异常:

A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll

Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

此代码在 async/await 更改首先更新该属性之前有效。我尝试在代码周围添加 Dispatcher.Invoke(),但我得到了同样的错误:

System.Windows.Application.Current.Dispatcher.Invoke(() => 
{ 
    this._customVariableGroups[index] = savedGroup; 
}); 

由于该字段最初是在后台线程上更新的,是否会导致从主线程更新它时出现问题?请注意,在 Visual Studio 的线程窗口中,此代码在主线程上执行。我不确定还需要做些什么才能让它发挥作用。

这是字段:

private ObservableCollection<CustomVariableGroup> _customVariableGroups; 

请您参考如下方法:

听起来您的 Collection View 是在后台线程上创建的,这通常不是一个好主意。

如果您使用async/await 加载数据(并且您的数据加载支持异步操作),那么您不需要使用后台线程。