0

在WPF中使用ObservableCollection實現生產者消費者模式我已經使用編組技術like in this example確保集合的事件在UI線程上分派,因爲正在工作線程上創建項目。CoreDispatcher WinRT是否與win8應用商店應用程序中的WPF Dispatcher相同?

在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

這裏是我做了什麼:

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)); 
     } 
相關問題