Using ThreadPoolTimer with Background Audio UWP

2019-04-15 11:04发布

问题:

I am making a UWP app using the BackgroundAudioTask. My app is working very well. Now I want to add in a TextBlock the Current position of the Audio played.

I was doing this method before implementing the audio Task:

private TimeSpan TotalTime;
        private DispatcherTimer timerRadioTime;

        private void radioPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            TotalTime = radioPlayer.NaturalDuration.TimeSpan;

            // Create a timer that will update the counters and the time slider
            timerRadioTime = new DispatcherTimer();
            timerRadioTime.Interval = TimeSpan.FromSeconds(1);
            timerRadioTime.Tick += TimerRadioTime_Tick;
            timerRadioTime.Start();
        }

        private void TimerRadioTime_Tick(object sender, object e)
        {
            //Check if the audio finished calculate it's total time
            if (radioPlayer.NaturalDuration.TimeSpan.TotalSeconds > 0)
            {
                if (TotalTime.TotalSeconds > 0)
                {
                    // Updating timer
                    TimeSpan currentPos = radioPlayer.Position;
                    var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
                    radioTimerBlock.Text = currentTime;
                }
            }
        }

When I implemented the Background Task it gave me an Exception. After researching I saw a suggestion of using ThreadPoolTimer instead of dispatcherTimer.

I tried writing this code (following this solution: Clock program employing ThreadPoolTimer C# uwp)

ThreadPoolTimer timer;

        // for displaying time only
        private void CurrentPlayer_MediaOpened(MediaPlayer sender, object args)
        {
            _clockTimer_Tick(timer);
        }


        private async void _clockTimer_Tick(ThreadPoolTimer timer)
        {
            var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
            await dispatcher.RunAsync(
             CoreDispatcherPriority.Normal, () =>
             {

                 // Your UI update code goes here!
                 if (CurrentPlayer.NaturalDuration.TotalSeconds > 0)
                 {
                     TimeSpan currentPos = CurrentPlayer.Position;
                     var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
                     CurrentPosition.Text = currentTime;
                 }

             });
        }

This is obviously not working. The app enters the method without updating my UI. I really don't understand what timer should be. Any Idea on how to make it run?

回答1:

Solution:

ThreadPoolTimer timer;

            // for displaying time only
            private void CurrentPlayer_MediaOpened(MediaPlayer sender, object args)
            {
                timer = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromSeconds(1));
            }


            private async void _clockTimer_Tick(ThreadPoolTimer timer)
            {
                var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
                await dispatcher.RunAsync(
                 CoreDispatcherPriority.Normal, () =>
                 {

                     // Your UI update code goes here!
                     if (CurrentPlayer.NaturalDuration.TotalSeconds < 0)
                     {
                         TimeSpan currentPos = CurrentPlayer.Position;
                         var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
                         CurrentPosition.Text = currentTime;
                     }

                 });
            }