Last active
October 27, 2024 14:56
-
-
Save DrkWzrd/67012cdd3c4b49ffbc407c0f49a0c81f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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