Skip to content

Instantly share code, notes, and snippets.

@DrkWzrd
Last active October 27, 2024 14:56
Show Gist options
  • Select an option

  • Save DrkWzrd/67012cdd3c4b49ffbc407c0f49a0c81f to your computer and use it in GitHub Desktop.

Select an option

Save DrkWzrd/67012cdd3c4b49ffbc407c0f49a0c81f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Concurrent;
using System.Threading;
public static class CancellationTokenExtensions
{
private static readonly ConcurrentDictionary<CancellationToken, string> _reasons = new();
private static readonly ConcurrentDictionary<CancellationToken, CancellationTokenSource> _sources = new();
// Method to create a CancellationToken with a reason
public static CancellationToken CreateCancellationToken(string reason)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
_reasons[token] = reason;
_sources[token] = cts;
return token;
}
// Method to create a CancellationToken from an existing CancellationTokenSource with a reason
public static CancellationToken CreateCancellationToken(CancellationTokenSource cts, string reason)
{
var token = cts.Token;
_reasons[token] = reason;
_sources[token] = cts;
return token;
}
// Method to create a CancellationToken that will be canceled after a delay with a reason
public static CancellationToken CreateCancellationToken(int millisecondsDelay, string reason)
{
var cts = new CancellationTokenSource(millisecondsDelay);
var token = cts.Token;
_reasons[token] = reason;
_sources[token] = cts;
return token;
}
// Method to create a linked CancellationToken with a reason
public static CancellationToken CreateLinkedCancellationToken(CancellationToken token1, CancellationToken token2, string reason)
{
var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(token1, token2);
var token = linkedCts.Token;
_reasons[token] = reason;
_sources[token] = linkedCts;
return token;
}
// Extension method to get the reason from an OperationCanceledException
public static string? GetReason(this OperationCanceledException exception)
{
return exception.CancellationToken != default && _reasons.TryGetValue(exception.CancellationToken, out var reason)
? reason
: null;
}
// Method to get the CancellationTokenSource associated with a CancellationToken
public static CancellationTokenSource? GetCancellationTokenSource(CancellationToken token)
{
return _sources.TryGetValue(token, out var cts) ? cts : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment