Skip to content

Commit

Permalink
Simplify attachment of the token
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Oct 25, 2024
1 parent 4fa27d6 commit dd6e61d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
14 changes: 6 additions & 8 deletions src/DotNext.Threading/Threading/LinkedCancellationTokenSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ namespace DotNext.Threading;
/// </remarks>
public abstract class LinkedCancellationTokenSource : CancellationTokenSource
{
private protected static readonly Action<object?, CancellationToken> 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);
Expand All @@ -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())
Expand Down
8 changes: 4 additions & 4 deletions src/DotNext.Threading/Threading/LinkedTokenSourceFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -172,13 +172,13 @@ internal MultipleLinkedCancellationTokenSource(ReadOnlySpan<CancellationToken> 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();
Expand Down

0 comments on commit dd6e61d

Please sign in to comment.