繁体   English   中英

DispatcherTimer仍在Stop()之后打勾事件,并将其设置为null

[英]The DispatcherTimer still tick event after Stop() and set to null

我正在编写一个应用程序以听音乐和观看视频。 在应用程序中,我有两个页面:1个用于播放音频播放代理(APA)-A页,一个用于播放视频(使用MediaElement)-B页。虽然WP8的APA有一个错误(我已经在这里问(我找到了解决方案-在MediaElement播放和关闭之前和之后停止APA两次)。

问题是,在A页面上,我每秒使用一个DispatcherTimer滴答来检查APA实例位置,当我离开此页面时,我有一个功能来停止此DispatcherTimer。

即使如此,如果我在A页上导航了几次,然后又导航到B页,则在1秒后,应用程序在if (BackgroundAudioPlayer.Instance.PlayerState == ...处抛出了异常。 DispatcherTimer仍然打勾?????如何强制停止此:(


我在这里发布了与DispatcherTimer相关的所有代码:

public DetailSongPage()
    {
        InitializeComponent();
        this.DataContext = App.Model;            
        BackgroundAudioPlayer.Instance.PlayStateChanged += APA_Instance_PlayStateChanged;                        
    }
DispatcherTimer timer = null;

private void APA_Instance_PlayStateChanged(object sender, EventArgs e)
    {
        if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
        {                
            UpdateTracking();
        }              
    }
protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);                           
        if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing || BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused)
        {   
            UpdateTracking();   
        }
    }
protected override void OnNavigatedFrom(NavigationEventArgs e)
    { 
        base.OnNavigatedFrom(e);
        timer.Stop();            
        timer.Tick -= timer_Tick;
        timer = null;            
    }
private void UpdateTracking()
    {
        sldTracking.Maximum = BackgroundAudioPlayer.Instance.Track.Duration.TotalMilliseconds;
        tbMaxTime.Text = string.Format(@"{0:mm\:ss}",BackgroundAudioPlayer.Instance.Track.Duration);
        // ^ these 2 lines update the UI for the slider and textblock 

        if (timer == null)
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += timer_Tick;
            timer.Start();
        }  
    }
    private void timer_Tick(object sender, EventArgs e)
    {
        if (this.timer != null)
        {
            try
            {                   
                if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing || BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused)
                {
                    sldTracking.Value = BackgroundAudioPlayer.Instance.Position.TotalMilliseconds;
                    tbCurrentTime.Text = string.Format(@"{0:mm\:ss}", BackgroundAudioPlayer.Instance.Position);
                }
            }
            catch
            {
                return;
            }
        }
    }

您可以在您的类中实现IDispose,在此实现中,停止计时器。 然后,无论何时离开页面,都请致电Dispose。 在“处置”中,您应该编写如下内容:

timer?.Stop();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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