在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
的恰当用途吗? Dispatcher
相同的静态访问方法,我是否需要将CoreDispatcher
从UI传递到编组代码?答案 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));
}