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

esy*_*tre 11 c# wpf timer backgroundworker

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

我以为我可以将System.Timers.Timer对象用于其Elapsed事件,然后调用a 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关如何进行的任何建议?

Jon*_*eet 41

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

除此之外,很难从你对"线程存在问题"的描述中说出什么是错的.

  • 说真的,我需要得到你的低挂果通知算法. (12认同)