0

在使用 WPF 实现生产者消费者模式时,ObservableCollection我使用了本示例中的封送处理技术,以确保在工作线程上创建项目时在 UI 线程上分派集合的事件。

在 winrt 中,我可以看到这样的封送处理Dispatcher方式:

public void AddItem<T>(ObservableCollection<T> oc, T item)
{
    if (Dispatcher.CheckAccess())
    {
        oc.Add(item);
    }
    else
    {
        Dispatcher.Invoke(new Action(t => oc.Add(t)), DispatcherPriority.DataBind, item);
    }
}

可以切换成CoreDispatcher这样:

public async void AddItem<T>(ObservableCollection<T> oc, T item)
{
    if (Dispatcher.HasThreadAccess)
    {
        oc.Add(item);
    }
    else
    {
        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { oc.Add(item); });
    }
}
  • 那是适当的使用CoreDispatcher吗?
  • 对于 winrt 中的基本并发生产者/消费者模式,是否有更好的方法来执行此操作?
  • Dispatcher没有与我需要CoreDispatcher从 UI 向下传递到编组代码相同的静态访问器方法吗?
4

1 回答 1

1

这是我所做的:

public Screen(IPreConfigurationService preConfigurationService, INavigationService navigationService)
        {
            _preConfigurationService = preConfigurationService;
            _navigationService = navigationService;
            if (!IsInDesignMode)
                _currentDispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }

        public string UserMessage
        {
            get { return _userMessage; }
            set
            {
                _userMessage = value;
                SafelyRaisePropertyChanged("UserMessage");
            }
        }
   protected void SafelyRaisePropertyChanged(string message)
        {
            if (!IsInDesignMode)
                _currentDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => RaisePropertyChanged(message));
        }
        protected void ExecuteOnDispatcher(Action action)
        {
            _currentDispatcher.RunAsync(CoreDispatcherPriority.Normal, action.Invoke);
        }

        protected void SendUserMessage(string message)
        {
            UserMessage = message;
            _currentDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => AlertOnError(message));
        }
于 2012-11-11T21:47:14.920 回答