新的DispatcherTimer与旧的DispatcherTimer一起创建,只应运行新的DispatcherTimer

时间:2016-04-26 12:20:02

标签: c# wpf mvvm timer dispatchertimer

前几天我遇到了一个问题。我已经发现了为什么会这样,但我从来没有遇到过这样的问题所以我不知道如何解决它。

我有一个应用程序,在DashboardView(主视图)中,DashboardViewModel中启动了DispatcherTimer。当Timer滴答时,我们从数据库中获取数据,此列表在View和ViewModel之间进行数据绑定。当有新数据导致数据库发生变化时,会发出声音。

用户可以转到其他视图。当用户返回DashboardView时,再次创建DashboardViewModel,DispatcherTimer也是如此。
现在有2个计时器,它们都会触发Tick事件,为用户创建一个令人困惑的场景。

这是我对应用程序现在发生的事情的观察:
我的计时器每分钟都会打勾。当我启动应用程序时,DashboardView#1打开。 DashboardViewModel#1启动,DispatcherTimer#1也启动 我切换到另一个视图,并对数据进行更新(一个新的电子邮件),这样当计时器滴答时,DashboardView中的列表将会改变并播放声音。
当计时器#1处于30秒时,我切换到新创建的DashboardView,从而创建View& ViewModel& Timer#2。 1分钟后,计时器#1滴答,有新数据,所以它更新数据库并播放声音,但视图中的列表不会更新。 我认为这是因为View#2显示在#1上。我知道,因为否则我会看到一个覆盖层,说它令人耳目一新 视图#2被数据绑定到ViewModel#2。计时器#1更新了ViewModel#1,因此我们看不到View#1,因为它被View#2替换/重叠,因此不会显示更改。 1分30秒后,定时器#2滴答,从数据库中获取数据,由于定时器#1已经使数据库更新,因此不会发出声音,并显示处于新状态的数据。登记/> (我希望这是有道理的)

所以,TLDR:有2个计时器正在运行,而只有1个应该处于活动状态(我认为是最新的计时器)。 我怎样才能做到这一点?

这是我现在拥有的DashboardViewModel(部分):

namespace QRM.ViewModel
{
    class DashboardListViewModel : INotifyPropertyChanged
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        DBServer dbServer = new DBServer();

        #region Constructor
        public DashboardListViewModel()
        {
            log.Info("Dashboard Initializing - Starting...");
            MyObservableCollection<View_server> listDashboard = new MyObservableCollection<View_server>();
            ListDashboard = dbServer.ReadDashboard();
            listBoxCommand = new RelayCommand(() => SelectionHasChanged());

            // Refresh to get all new emails, errors, etc.
            GetListDashboard();

            IsRefreshing = Visibility.Collapsed;

            // Make a timer to renew the data in the Dashboard automatically. 
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = Properties.Settings.Default.Timer_interval; // hours, minutes, seconds.
            timer.Start();

            //Receive the Notification sent after DashboardDetailsViewModel has handled the button commands, and call a respond method for the List.
            App.Messenger.Register("RefreshServers", (Action)(() => GetListDashboard()));
            App.Messenger.Register("ClearSelection", (Action)(() => SelectedServer = null));
            App.Messenger.Register("ErrorSolved", (Action)(() => KeepSelection(selectedServer)));
            App.Messenger.Register("WarningSound", (Action)(() => HasNewError = true));
            log.Info("Dashboard Initializing - Done.");
        }
        #endregion

        #region Get list dashboard
        private void GetListDashboard()
        {
            HasNewError = false;
            log.Info("Dashboard - Checking for Email...");

            // The old Outlook class and methods
            //EmailManager checkMail = new EmailManager();
            //checkMail.GetEmail();

            // First, check for mail.
            IMAPManager checkMail = new IMAPManager();
            checkMail.GetEmail();

            log.Info("Dashboard - Checking for linked Errors...");
            // Check if the emails have Errors linked to them. If not, add the Error from the Email to the DB
            ErrorManager checkError = new ErrorManager();
            checkError.GetNewErrors();

            log.Info("Dashboard List - Starting...");
            // Load the dashboard.
            ListDashboard = dbServer.ReadDashboard();
            System.Diagnostics.Debug.WriteLine("REFRESHED THE DASHBOARD");
            log.Info("Dashboard List - Done.");
        }

        private void KeepSelection(View_server keepSelection)
        {
            GetListDashboard();
            SelectedServer = keepSelection;
            SelectionHasChanged();
        }
        #endregion

        #region Timer
        //This method runs every time the timer ticks.
        private async void timer_Tick(object sender, EventArgs e)
        {
            log.Info("Dashboard - Refreshing...");
            System.Diagnostics.Debug.WriteLine(">>Timer tick");
            IsRefreshing = Visibility.Visible;

            // To make sure the overlay is visible to the user, let it be on screen for at least a second (2x half a second)
            await Task.Delay(500);

            if (selectedServer != null)
            {
                KeepSelection(selectedServer);
            }
            else
            {
                GetListDashboard();
            }

            // 2nd half second.
            await Task.Delay(500);
            IsRefreshing = Visibility.Collapsed;

            if (hasNewError == true)
            {
                System.Diagnostics.Debug.WriteLine("List has new error");
                PlayWarningSound();
                HasNewError = false;
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("List has no new error");
                HasNewError = false;
            }
            System.Diagnostics.Debug.WriteLine(">>End timer");

            log.Info("Dashboard - Refreshed.");
        }        
        #endregion
    }
}

1 个答案:

答案 0 :(得分:1)

这里有一些问题。让我们从最基本的第一个开始:

<强>清理

当处理或关闭DashboardListViewModel时,您需要取消DispatcherTimer.Tick事件处理程序,调用.Stop(),然后调用.Finalize()MSDN。这样可以确保正确清理System.Windows.Threading.DispatcherTimer

Async / Await&amp;事件处理程序

此外,DispatcherTimer.Tick事件处理程序定义为async void。这是async关键字的错误用法。而是使用它:

private void timer_Tick(object sender, EventArgs e)
{
    log.Info("Dashboard - Refreshing...");
    System.Diagnostics.Debug.WriteLine(">>Timer tick");
    IsRefreshing = Visibility.Visible;

    // To make sure the overlay is visible to the user, let it be on screen for at least a second (2x half a second)
    Thread.Sleep(500);

    if (selectedServer != null)
    {
        KeepSelection(selectedServer);
    }
    else
    {
        GetListDashboard();
    }

    // 2nd half second.
    Thread.Sleep(500);
    IsRefreshing = Visibility.Collapsed;

    if (hasNewError == true)
    {
        System.Diagnostics.Debug.WriteLine("List has new error");
        PlayWarningSound();
        HasNewError = false;
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("List has no new error");
        HasNewError = false;
    }
    System.Diagnostics.Debug.WriteLine(">>End timer");

    log.Info("Dashboard - Refreshed.");
}

我通常不建议使用Thread.Sleep但是因为你已经在线程计时器的上下文中这是有道理的。

最后一个问题

您是否确定可以多次调用App.Messenger.Register,因为每次实例化视图模型时都会发生这种情况?我会想象在static背景下,这只是你想做的一次。