diff --git a/src/DotNext.Threading/Threading/LinkedCancellationTokenSource.cs b/src/DotNext.Threading/Threading/LinkedCancellationTokenSource.cs index 6aca9ee86..6499bee7c 100644 --- a/src/DotNext.Threading/Threading/LinkedCancellationTokenSource.cs +++ b/src/DotNext.Threading/Threading/LinkedCancellationTokenSource.cs @@ -13,12 +13,14 @@ namespace DotNext.Threading; /// public abstract class LinkedCancellationTokenSource : CancellationTokenSource { - private protected static readonly Action CancellationCallback; + private Atomic.Boolean status; - static LinkedCancellationTokenSource() + private protected LinkedCancellationTokenSource() => CancellationOrigin = Token; + + private protected CancellationTokenRegistration Attach(CancellationToken token) { - CancellationCallback = OnCanceled; - + return token.UnsafeRegister(OnCanceled, this); + static void OnCanceled(object? source, CancellationToken token) { Debug.Assert(source is LinkedCancellationTokenSource); @@ -27,10 +29,6 @@ static void OnCanceled(object? source, CancellationToken token) } } - private Atomic.Boolean status; - - private protected LinkedCancellationTokenSource() => CancellationOrigin = Token; - private void Cancel(CancellationToken token) { if (status.FalseToTrue()) diff --git a/src/DotNext.Threading/Threading/LinkedTokenSourceFactory.cs b/src/DotNext.Threading/Threading/LinkedTokenSourceFactory.cs index 3650e3128..7254fb083 100644 --- a/src/DotNext.Threading/Threading/LinkedTokenSourceFactory.cs +++ b/src/DotNext.Threading/Threading/LinkedTokenSourceFactory.cs @@ -141,8 +141,8 @@ internal Linked2CancellationTokenSource(in CancellationToken token1, in Cancella Debug.Assert(token1.CanBeCanceled); Debug.Assert(token2.CanBeCanceled); - registration1 = token1.UnsafeRegister(CancellationCallback, this); - registration2 = token2.UnsafeRegister(CancellationCallback, this); + registration1 = Attach(token1); + registration2 = Attach(token2); } protected override void Dispose(bool disposing) @@ -172,13 +172,13 @@ internal MultipleLinkedCancellationTokenSource(ReadOnlySpan t { if (token != first && token.CanBeCanceled) { - writer.Add(token.UnsafeRegister(CancellationCallback, this)); + writer.Add(Attach(token)); } } if (first.CanBeCanceled && writer.WrittenCount > 0) { - writer.Add(first.UnsafeRegister(CancellationCallback, this)); + writer.Add(Attach(first)); } registrations = writer.DetachOrCopyBuffer();