From ee63cad39eb85e8f02142a081e179fc9d4a56275 Mon Sep 17 00:00:00 2001 From: cadon Date: Mon, 27 Nov 2023 22:05:11 +0100 Subject: [PATCH] avoid unneccessary complexity of cancellationTokenSource disposal --- ARKBreedingStats/AsbServer/Connection.cs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/ARKBreedingStats/AsbServer/Connection.cs b/ARKBreedingStats/AsbServer/Connection.cs index dc5c9672..2b7a7010 100644 --- a/ARKBreedingStats/AsbServer/Connection.cs +++ b/ARKBreedingStats/AsbServer/Connection.cs @@ -4,7 +4,6 @@ using System.Net.Http; using System.Text; using System.Text.RegularExpressions; -using System.Threading; using ARKBreedingStats.importExportGun; using ARKBreedingStats.Library; @@ -17,7 +16,7 @@ internal static class Connection { private const string ApiUri = "https://export.arkbreeder.com/api/v1/"; - private static CancellationTokenSource _cancellationTokenSource; + private static SimpleCancellationToken _lastCancellationToken; public static async void StartListeningAsync(IProgress<(string jsonText, string serverHash, string message)> progressDataSent, string token = null) { @@ -25,8 +24,8 @@ public static async void StartListeningAsync(IProgress<(string jsonText, string // stop previous listening if any StopListening(); - _cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = _cancellationTokenSource.Token; + var cancellationToken = new SimpleCancellationToken(); + _lastCancellationToken = cancellationToken; try { @@ -102,12 +101,11 @@ public static async void StartListeningAsync(IProgress<(string jsonText, string public static void StopListening() { - if (_cancellationTokenSource == null) + if (_lastCancellationToken == null) return; // nothing to stop - _cancellationTokenSource.Cancel(); - _cancellationTokenSource.Dispose(); - _cancellationTokenSource = null; + _lastCancellationToken.Cancel(); + _lastCancellationToken = null; } /// @@ -155,5 +153,14 @@ public static string CreateNewToken() return new string(token); } + + /// + /// Simple replacement of CancellationTokenSource to avoid unnecessary complexities with disposal of CTS when the token is still in use. + /// + private class SimpleCancellationToken + { + public bool IsCancellationRequested; + public void Cancel() => IsCancellationRequested = true; + } } }