You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用CollectionViewSource.GetDefaultView为何改变await恢复线程引发异常

为何调用CollectionViewSource.GetDefaultView会导致await恢复线程与原线程不一致?

先看以下单元测试代码:

[TestMethod]
public void MVCE()
{
    asyncMethodNoCollectionView().Wait(); // 不会报错
    asyncMethodWithCollectionView().Wait(); // 报错
}

private async Task asyncMethodNoCollectionView()
{
    var collection = new ObservableCollection<string>();
    await Task.Run(() =>
    {
        Task.Delay(4000).Wait();
    });
    collection.Add("hello");
}

private async Task asyncMethodWithCollectionView()
{
    var collection = new ObservableCollection<string>();
    var view = CollectionViewSource.GetDefaultView(collection);
    await Task.Run(() =>
    {
        Task.Delay(4000).Wait();
    });
    collection.Add("hello");
}

调用CollectionViewSource.GetDefaultView(collection);后,第二个方法里的collection.Add("hello")会抛出异常:

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

该现象在多台机器、不同负载下多次测试均一致。

我的理解是:第一个方法中await恢复的线程就是创建ObservableCollection的线程,所以添加元素不会报错;但第二个方法中await恢复的线程并非创建集合的线程,因此触发了集合必须在原线程编辑的限制。

核心疑问:为何调用CollectionViewSource.GetDefaultView会导致恢复线程与原线程始终不同?

(注:曾看到过相关问题,但无法明确其与当前疑问的关联逻辑)

内容的提问来源于stack exchange,提问作者Arthur Attout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:20:36