[英]Refresh UI with a Timer in WPF (with BackgroundWorker?)
我們在WPF中有一個應用程序,它通過ObservableCollection顯示數據。 5分鍾后,我想刷新數據。
我以為我可以將System.Timers.Timer
對象用於其Elapsed
事件,然后調用BackgroundWorker
來調用啟動作業的方法。 該方法位於ViewModel類上。
但似乎線程存在問題。
所以我嘗試了Dispatcher,但同樣的事情。
這是我的(簡化和未優化)代碼:
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationController"/> class.
/// </summary>
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.