CollectionView 不支持从与调度程序线程不同的线程更改其源集合 - 由调度程序线程引起

pin*_*2k4 1 c# multithreading observablecollection collectionview

我有一个 ObservableCollection 和一个使用 OC 作为源的 ICollectionView:

private ObservableCollection<Comment> _Comments = new ObservableCollection<Comment>();
/// <summary>
/// Comments on the account
/// </summary>
[BsonElement("comments")]
public ObservableCollection<Comment> Comments
{
    get
    {
        return _Comments;
    }
    set
    {
        _Comments = value;
        OnPropertyChanged("Comments");
        OnPropertyChanged("CommentsSorted");
    }
}
private ICollectionView _CommentsSorted;
/// <summary>
/// Sorted list (reverse order) of the comments
/// </summary>
[BsonIgnore]
public ICollectionView CommentsSorted
{
    get
    {
        return _CommentsSorted;
    }
    set
    {
        _CommentsSorted = value;
        OnPropertyChanged("CommentsSorted");
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个命令,运行:

obj.Comments.Add(new Comment(Message));
Run Code Online (Sandbox Code Playgroud)

其中 obj 是包含可观察集合的类的实例。

调用此行时,我遇到以下异常:

System.NotSupportedException:“这种类型的 CollectionView 不支持从与 Dispatcher 线程不同的线程更改其 SourceCollection。”

我已经打开“调试”>“窗口”>“线程”面板,它在主线程上运行。我尝试将其放入 App.Current.Dispatcher.Invoke(...) 中,但没有成功。

我不明白为什么会发生这种情况。更奇怪的是,我能够在同一类的另一个实例上运行得很好,完全没有问题,该实例是同时创建的(在同一调用中从我的数据库返回并一起创建)。第一个我添加了评论没有问题,并且每次仍然可以,但我尝试过的所有其他人都失败了。

Nei*_*l B 5

就我而言,问题是集合视图在任务中刷新。后来从主 UI 线程添加到集合中导致了异常。

构建视图模型时,集合在延迟任务中刷新。

public MainVM()
{
    //other code...
    Task.Delay(100).ContinueWith(_ => UpdatePreferences());
}


public void UpdatePreferences()
{
    //other code..
    CollectionViewSource.GetDefaultView(Data.Customers).Refresh();
}
Run Code Online (Sandbox Code Playgroud)

我能够通过调用调度程序来解决该问题。

Task.Delay(100).ContinueWith(_ => App.Current.Dispatcher.Invoke(()=> UpdatePreferences()));
Run Code Online (Sandbox Code Playgroud)