WPF-支持异步操作的ObservableCollection-AsyncObservableCollection

 

在进行WPF开发过程中,需要从一个新的线程中操作ObservableCollection,结果程序抛出一个NotSupportedException的错误

 

public class AsyncObservableCollection<T> : ObservableCollection<T>
{
    //获取当前线程的SynchronizationContext对象
    private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
    public AsyncObservableCollection() { }
    public AsyncObservableCollection(IEnumerable<T> list) : base(list) { }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
          
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            //如果操作发生在同一个线程中,不需要进行跨线程执行         
            RaiseCollectionChanged(e);
        }
        else
        {
            //如果不是发生在同一个线程中
            //准确说来,这里是在一个非UI线程中,需要进行UI的更新所进行的操作         
            _synchronizationContext.Post(RaiseCollectionChanged, e);
        }
    }
    private void RaiseCollectionChanged(object param)
    {
        // 执行         
        base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
    }
    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            // Execute the PropertyChanged event on the current thread             
            RaisePropertyChanged(e);
        }
        else
        {
            // Post the PropertyChanged event on the creator thread             
            _synchronizationContext.Post(RaisePropertyChanged, e);
        }
    }
    private void RaisePropertyChanged(object param)
    {
        // We are in the creator thread, call the base implementation directly         
        base.OnPropertyChanged((PropertyChangedEventArgs)param);
    }
}
View Code

 

https://blog.csdn.net/juns6/article/details/50964496

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值