CoreDispatcher WinRT是否相当于win8应用程序商店应用程序中的WPF Dispatcher?

时间:2012-11-10 17:33:22

标签: marshalling observablecollection winrt-xaml windows-store-apps

在WPF中使用ObservableCollection实现生成器使用者模式时,我使用了编组技术like in this example来确保在工作线程上创建项目时在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传递到编组代码?

1 个答案:

答案 0 :(得分: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));
        }