Skip to content

Commit

Permalink
Ensure that the progress update task stops when the sound stops (so t…
Browse files Browse the repository at this point in the history
…hat it's not running indefinitely)
  • Loading branch information
micahmo committed Aug 19, 2019
1 parent 96b28c1 commit 4a5dc1a
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions SoundBoard/Buttons.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -1090,8 +1094,14 @@ private void SetDefaultText()
SetUpContextMenu();
}

private void UpdateProgressAction()
/// <summary>
/// Returns false as long as there is still processing to perform.
/// Returns true when progress no longer needs to be updated.
/// </summary>
private bool UpdateProgressAction()
{
bool result = false;

double maxSeconds = _audioFileReader.TotalTime.TotalMilliseconds;
double curSeconds = _stopWatch.Elapsed.TotalMilliseconds;

Expand All @@ -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<bool> 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);
}
}

Expand Down Expand Up @@ -1552,6 +1567,8 @@ private set

private Point? _mouseDownPosition;

private CancellationTokenSource _progressBarCancellationToken;

#endregion

#region Private consts
Expand Down

0 comments on commit 4a5dc1a

Please sign in to comment.