From 4a5dc1a769712538baf68629047dd98426a35f25 Mon Sep 17 00:00:00 2001 From: Micah Morrison Date: Mon, 19 Aug 2019 16:46:58 -0400 Subject: [PATCH] Ensure that the progress update task stops when the sound stops (so that it's not running indefinitely) --- SoundBoard/Buttons.cs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/SoundBoard/Buttons.cs b/SoundBoard/Buttons.cs index 195b5a8..6607b55 100644 --- a/SoundBoard/Buttons.cs +++ b/SoundBoard/Buttons.cs @@ -608,6 +608,8 @@ private void ChooseSoundMenuItem_Click(object sender, RoutedEventArgs e) private void SoundStoppedHandler(object sender, StoppedEventArgs e) { + _progressBarCancellationToken?.Cancel(); + _audioFileReader.Position = 0; // Hide the additional buttons @@ -922,8 +924,10 @@ public async void StartSound() _player.Play(); // Begin updating progress bar - CancellationTokenSource tokenSource = new CancellationTokenSource(); - await UpdateProgressTask(UpdateProgressAction, TimeSpan.FromMilliseconds(5), tokenSource.Token); + _progressBarCancellationToken?.Cancel(); + _progressBarCancellationToken?.Dispose(); + _progressBarCancellationToken = new CancellationTokenSource(); + UpdateProgressTask(UpdateProgressAction, TimeSpan.FromMilliseconds(5), _progressBarCancellationToken.Token); } catch (Exception ex) { @@ -1090,8 +1094,14 @@ private void SetDefaultText() SetUpContextMenu(); } - private void UpdateProgressAction() + /// + /// Returns false as long as there is still processing to perform. + /// Returns true when progress no longer needs to be updated. + /// + private bool UpdateProgressAction() { + bool result = false; + double maxSeconds = _audioFileReader.TotalTime.TotalMilliseconds; double curSeconds = _stopWatch.Elapsed.TotalMilliseconds; @@ -1109,16 +1119,21 @@ private void UpdateProgressAction() else { SoundProgressBar.Visibility = Visibility.Hidden; + result = true; } } + + return result; } - private async Task UpdateProgressTask(Action action, TimeSpan interval, CancellationToken token) + private async void UpdateProgressTask(Func action, TimeSpan interval, CancellationToken token) { - while (true) + bool result = false; + + while (token.IsCancellationRequested == false || result == false) { - action(); - await Task.Delay(interval, token); + result = action(); + await Task.Delay(interval); } } @@ -1552,6 +1567,8 @@ private set private Point? _mouseDownPosition; + private CancellationTokenSource _progressBarCancellationToken; + #endregion #region Private consts