繁体   English   中英

在WPF中使用计时器刷新UI(使用BackgroundWorker?)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM