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

问题描述 投票:0回答:1

我有一个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");
    }
}

我有一个运行的命令:

obj.Comments.Add(new Comment(Message));

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

在拨打此行时,我遇到以下异常:

System.NotSupportedException:'此类型的CollectionView不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改。'

我已经打开了Debug> Windows> Threads面板,它正在主线程上运行。我尝试将其放入App.Current.Dispatcher.Invoke(...),不走运。

我不知道为什么会这样。使事情变得奇怪的是,我能够在同一时间创建的同一类的另一个实例上(在同一调用中从我的数据库中返回并一起创建)很好地运行,没有任何问题。我第一个添加评论没有问题,每次都可以,但是我尝试过的所有其他评论都失败了。

c# multithreading observablecollection collectionview
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.