From ee0b40d65795252f4bb810f1bae424478ce7715d Mon Sep 17 00:00:00 2001 From: Amos Date: Sun, 7 Jul 2024 01:30:40 +0100 Subject: [PATCH] Improve cancellation token handling in Utilities.cs (#331) 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. --- SharedLibraryCore/Utilities.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/SharedLibraryCore/Utilities.cs b/SharedLibraryCore/Utilities.cs index f7e2a322..34843cab 100644 --- a/SharedLibraryCore/Utilities.cs +++ b/SharedLibraryCore/Utilities.cs @@ -1386,16 +1386,21 @@ public static async Task 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) @@ -1409,6 +1414,7 @@ async Task OnResponse(ClientMessageEvent messageEvent, CancellationToken cancell if (await validator(response)) { + // ReSharper disable once AccessToDisposedClosure clientResponse.Set(); } else