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の基本的な同時生産者/消費者パターンに対してこれを行うためのより良い方法はありますか?
  • UIからマーシャリングコードDispatcherに渡す必要があるのと同じ静的アクセサーメソッドがない場合はどうなりますか?CoreDispatcher
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 に答える