在WPF中使用计时器刷新UI(使用BackgroundWorker?)
我们在WPF中有一个应用程序,通过ObservableCollection显示数据。 5分钟后,我想刷新数据。
我以为我可以将System.Timers.Timer
对象用于其Elapsed
事件,然后调用BackgroundWorker
来调用启动作业的方法。 该方法位于ViewModel类上。
但似乎线程存在问题。
所以我尝试了Dispatcher,但同样的事情。
这是我的(简化和未优化)代码:
/// /// Initializes a new instance of the class. /// public ApplicationController() { CreateDefaultTabs(); Timer timer = new Timer(20000); //20 secs for testing purpose. timer.AutoReset = true; timer.Enabled = true; timer.Elapsed += new ElapsedEventHandler(OnTimeBeforeRefreshElapsed); timer.Start(); } private void OnTimeBeforeRefreshElapsed(object sender, ElapsedEventArgs e) { Dispatcher.CurrentDispatcher.Invoke(new Action(() => { RefreshData(); })); Dispatcher.CurrentDispatcher.Invoke(new Action(() => { UpdateLayout(); })); } private void RefreshData() { foreach (object tab in _tabItems) { if (tab is TitleDetailsView) { TitleDetailsViewModel vm = ((TitleDetailsView)tab).DataContext as TitleDetailsViewModel; vm.Refresh(); } } } private void UpdateLayout() { foreach (object tab in _tabItems) { if (tab is TitleDetailsView) { TitleDetailsViewModel vm = ((TitleDetailsView)tab).DataContext as TitleDetailsViewModel; vm.HandleGetTitleBySymbolResponse(); } } }
关于我应该如何进行的任何建议?
为什么不使用DispatcherTimer
? 这将在调度程序线程中“打勾”。
除此之外,很难从你对“线程存在问题”的描述中说出什么是错的。
这个答案解释了更新UI时使用Timer vs DispatcherTimer的问题。 https://stackoverflow.com/a/2258909/1698182
我没有试过这个,但对于使用线程的定期工作项做大部分工作,看起来它会起作用。 http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj248676.aspx