Skip to content

Commit

Permalink
avoid unneccessary complexity of cancellationTokenSource disposal
Browse files Browse the repository at this point in the history
  • Loading branch information
cadon committed Nov 27, 2023
1 parent 7ce01a4 commit ee63cad
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions ARKBreedingStats/AsbServer/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using ARKBreedingStats.importExportGun;
using ARKBreedingStats.Library;

Expand All @@ -17,16 +16,16 @@ 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)
{
if (string.IsNullOrEmpty(token)) return;

// stop previous listening if any
StopListening();
_cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _cancellationTokenSource.Token;
var cancellationToken = new SimpleCancellationToken();
_lastCancellationToken = cancellationToken;

try
{
Expand Down Expand Up @@ -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;
}

/// <summary>
Expand Down Expand Up @@ -155,5 +153,14 @@ public static string CreateNewToken()

return new string(token);
}

/// <summary>
/// Simple replacement of CancellationTokenSource to avoid unnecessary complexities with disposal of CTS when the token is still in use.
/// </summary>
private class SimpleCancellationToken
{
public bool IsCancellationRequested;
public void Cancel() => IsCancellationRequested = true;
}
}
}

0 comments on commit ee63cad

Please sign in to comment.