使用 WPF 中的计时器刷新 UI(使用 BackgroundWorker?) [英] Refresh UI with a Timer in WPF (with BackgroundWorker?)

查看:29
本文介绍了使用 WPF 中的计时器刷新 UI(使用 BackgroundWorker?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在 WPF 中有一个应用程序,它通过 ObservableCollection 显示数据.5 分钟后,我想刷新数据.

We have an application in WPF that shows data via ObservableCollection. After 5 minutes, I want to refresh the data.

我想我可以将 System.Timers.Timer 对象用于其 Elapsed 事件,然后调用 BackgroundWorker 来调用该方法开始工作.该方法位于 ViewModel 类上.

I thought I could use the System.Timers.Timer object for its Elapsed event and then call a BackgroundWorker to call the method that starts the job. The method is on a ViewModel class.

但线程似乎有问题.

所以我尝试使用 Dispatcher,但还是同样的事情.

So I tried with the Dispatcher, but same thing again.

这是我的(简化而不是优化的)代码:

Here's my (simplified and not optimized) code :

/// <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();
        }
    }
}

对我应该如何进行有什么建议吗?

Any suggestions on how I should proceed?

推荐答案

为什么不使用 DispatcherTimer?这将在调度程序线程中打勾".

Why not use a DispatcherTimer? That will "tick" in the dispatcher thread already.

除此之外,仅凭您对线程有问题"的描述,很难说有什么问题.

Beyond that, it's hard to say what's wrong just from your description of "there's a problem with the threads".

这篇关于使用 WPF 中的计时器刷新 UI(使用 BackgroundWorker?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆