Skip to content

Commit

Permalink
Improve cancellation token handling in Utilities.cs (#331)
Browse files Browse the repository at this point in the history
A using statement was added to ensure proper disposal of the CancellationTokenSource. Additional error handling was also included to catch an OperationCanceledException and prevent it from causing unintended side effects. The client response is now properly disposed in the finally block.
  • Loading branch information
Ayymoss authored Jul 7, 2024
1 parent 036a467 commit ee0b40d
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion SharedLibraryCore/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1386,16 +1386,21 @@ public static async Task<string> PromptClientInput(this EFClient client, string
IGameEventSubscriptions.ClientMessaged += OnResponse;
await client.TellAsync([prompt], token);

var tokenSource = new CancellationTokenSource(DefaultCommandTimeout);
using var tokenSource = new CancellationTokenSource(DefaultCommandTimeout);
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(tokenSource.Token, token);

clientResponse.Wait(linkedTokenSource.Token);

return response;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
IGameEventSubscriptions.ClientMessaged -= OnResponse;
clientResponse.Dispose();
}

async Task OnResponse(ClientMessageEvent messageEvent, CancellationToken cancellationToken)
Expand All @@ -1409,6 +1414,7 @@ async Task OnResponse(ClientMessageEvent messageEvent, CancellationToken cancell

if (await validator(response))
{
// ReSharper disable once AccessToDisposedClosure
clientResponse.Set();
}
else
Expand Down

0 comments on commit ee0b40d

Please sign in to comment.