C# 将异步消息分派到同步上下文中

发布时间 2023-09-12 17:07:59作者: 潇潇烟雨

封装一个异步方法类:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;

namespace K.Controls.Helper
{
    public class AsyncObervableCollection<T> : ObservableCollection<T>
    {
        private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
        public AsyncObervableCollection()
        {

        }

        public AsyncObervableCollection(IEnumerable<T> list) : base(list)
        {

        }
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (SynchronizationContext.Current == _synchronizationContext)
            {
                RaiseCollectionChanged(e);
            }
            else
            {
                _synchronizationContext.Post(RaiseCollectionChanged, e);
            }
        }

        private void RaiseCollectionChanged(object param)
        {
            base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
        }

        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (SynchronizationContext.Current == _synchronizationContext)
            {
                RaisePropertychanged(e);
            }
            else
            {
                _synchronizationContext.Post(RaisePropertychanged, e);
            }
        }

        private void RaisePropertychanged(object param)
        {
            base.OnPropertyChanged((PropertyChangedEventArgs)param);
        }

    }
}

 

调用以上封装类中的方法:

public class QueryItemModel
{
    private AsyncObervableCollection<QueryItem> items;
        public AsyncObervableCollection<QueryItem> Items
        {
            get { return items; }
            set
            {
                items = value;
                OnPropertyChanged(nameof(Items));
            }
        }
    
    public QueryItemModel()
        {
            Items = new AsyncObervableCollection<QueryItem>();
        }
}


public QueryItemModel QueryItemModel { get; set; }
public QueryItemViewModel()
{
    QueryItemModel = new QueryItemModel();
}

void QueryItem()
{
    QueryItemModel.Items.Clear();
    var item = chi.Adapt<QueryItem>();
    item.Plu = result.Data.plu;
    item.Sale_Price = chi.Sale_Price;
    item.IsQuery = "0";
    item.Key = chi.key;
    QueryItemModel.Items.Add(item);
}

  -