Skip to content

Commit

Permalink
Fixed deadlock when manually restarting the wait.
Browse files Browse the repository at this point in the history
  • Loading branch information
skst committed May 5, 2024
1 parent 029c6cd commit 905e3b8
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions WatchAndWait.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ private static async Task TrySleepComputerAsync(TimeSpan initialDelay)
// Switch to background to do the wait
await Shared.ThreadSwitcher.ResumeBackgroundAsync();

bool bManualRestart = false;
try
{
// If we delay before sleeping, we need to be able to cancel it.
Expand All @@ -118,11 +119,7 @@ private static async Task TrySleepComputerAsync(TimeSpan initialDelay)
await Task.Delay(Properties.Settings.Default.DelayBeforeSleep, localTokenSource.Token);
}

if (!SleepComputer())
{
// Sleep failed, so we must restart the wait manually.
await TrySleepComputerAsync(TimeSpan.Zero).ConfigureAwait(continueOnCapturedContext: false);
}
bManualRestart = !SleepComputer();
}
catch (TaskCanceledException ex) // From CancellationToken.Cancel()
{
Expand All @@ -141,12 +138,18 @@ private static async Task TrySleepComputerAsync(TimeSpan initialDelay)
TrySleepComplete.Set();
}

/// Note: We have to do this AFTER the above `finally` so that the event is set.
/// Then, when we try to sleep again, the wait for the event will succeed (not block).
#if DEBUG
TheWindow.WriteWarning("DEBUG: Skipped sleeping computer. Simulate resuming...");
/// Simulate resuming (also give us time to set the <see cref="TrySleepComplete"/> event.
/// Note: We have to do this AFTER the above `finally` so that the event is set.
/// Then, when we try to sleep again, the wait for the event will succeed (not block).
await TrySleepComputerAsync(Properties.Settings.Default.DelayAfterResume);
await TrySleepComputerAsync(Properties.Settings.Default.DelayAfterResume).ConfigureAwait(continueOnCapturedContext: false);
#else
if (bManualRestart)
{
// Sleep failed, so we must restart the wait manually.
await TrySleepComputerAsync(TimeSpan.Zero).ConfigureAwait(continueOnCapturedContext: false);
}
#endif
}

Expand Down

0 comments on commit 905e3b8

Please sign in to comment.