【问题标题】:Refresh UI with a Timer in WPF (with BackgroundWorker?)在 WPF 中使用计时器刷新 UI(使用 BackgroundWorker?)
【发布时间】:2010-10-20 19:27:11
【问题描述】:

我们在 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();
        }
    }
}

关于我应该如何进行的任何建议?

【问题讨论】:

  • 线程有问题?究竟是什么问题?

标签: c# wpf timer backgroundworker


【解决方案1】:

为什么不使用DispatcherTimer?这已经在调度程序线程中“打勾”了。

除此之外,仅从您对“线程有问题”的描述很难说出了什么问题。

【讨论】:

  • 说真的,我需要得到你的低挂水果通知算法。
【解决方案2】:

此答案解释了在更新 UI 时使用 Timer 与 DispatcherTimer 的问题。 https://stackoverflow.com/a/2258909/1698182

我还没有尝试过,但是对于将使用线程完成大部分工作的定期工作项,这看起来可以解决问题。 http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj248676.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    相关资源
    最近更新 更多