Cancel some delay tasks if they're not being used

This commit is contained in:
Kwoth
2022-01-23 04:14:16 +01:00
parent c6b0d75fd7
commit a402f33a4c
2 changed files with 19 additions and 3 deletions

View File

@@ -97,14 +97,23 @@ public class Blackjack
private async Task PromptUserMove(User usr) private async Task PromptUserMove(User usr)
{ {
var pause = Task.Delay(20000); //10 seconds to decide using var cts = new CancellationTokenSource();
var pause = Task.Delay(20000, cts.Token); //10 seconds to decide
CurrentUser = usr; CurrentUser = usr;
currentUserMove = new(); currentUserMove = new();
await PrintState(); await PrintState();
// either wait for the user to make an action and // either wait for the user to make an action and
// if he doesn't - stand // if he doesn't - stand
var finished = await Task.WhenAny(pause, currentUserMove.Task); var finished = await Task.WhenAny(pause, currentUserMove.Task);
if (finished == pause) await Stand(usr); if (finished == pause)
{
await Stand(usr);
}
else
{
cts.Cancel();
}
CurrentUser = null; CurrentUser = null;
currentUserMove = null; currentUserMove = null;
} }

View File

@@ -146,7 +146,8 @@ public sealed class AyuVoiceStateService : INService
await SendJoinVoiceChannelInternalAsync(guildId, channelId); await SendJoinVoiceChannelInternalAsync(guildId, channelId);
// create a delay task, how much to wait for gateway response // create a delay task, how much to wait for gateway response
var delayTask = Task.Delay(2500); using var cts = new CancellationTokenSource();
var delayTask = Task.Delay(2500, cts.Token);
// either delay or successful voiceStateUpdate // either delay or successful voiceStateUpdate
var maybeUpdateTask = Task.WhenAny(delayTask, voiceStateUpdatedSource.Task); var maybeUpdateTask = Task.WhenAny(delayTask, voiceStateUpdatedSource.Task);
@@ -156,8 +157,14 @@ public sealed class AyuVoiceStateService : INService
// wait for both to end (max 1s) and check if either of them is a delay task // wait for both to end (max 1s) and check if either of them is a delay task
var results = await Task.WhenAll(maybeUpdateTask, maybeServerTask); var results = await Task.WhenAll(maybeUpdateTask, maybeServerTask);
if (results[0] == delayTask || results[1] == delayTask) if (results[0] == delayTask || results[1] == delayTask)
{
// if either is delay, return null - connection unsuccessful // if either is delay, return null - connection unsuccessful
return null; return null;
}
else
{
cts.Cancel();
}
// if both are succesful, that means we can safely get // if both are succesful, that means we can safely get
// the values from completion sources // the values from completion sources