Skip to content

Commit

Permalink
Create cancellation token registration wrapper only when it's needed (#…
Browse files Browse the repository at this point in the history
…45075)

Co-authored-by: Stephen Toub <stoub@microsoft.com>
  • Loading branch information
marek-safar and stephentoub authored Nov 23, 2020
1 parent bf302de commit 7218577
Showing 1 changed file with 2 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,6 @@ public readonly struct CancellationToken
private readonly CancellationTokenSource? _source;
// !! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid

private static readonly Action<object?> s_actionToActionObjShunt = obj =>
{
Debug.Assert(obj is Action, $"Expected {typeof(Action)}, got {obj}");
((Action)obj)();
};

/// <summary>
/// Returns an empty CancellationToken value.
/// </summary>
Expand Down Expand Up @@ -136,12 +130,7 @@ public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSourc
/// <returns>The <see cref="System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to unregister the callback.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback) =>
Register(
s_actionToActionObjShunt,
callback ?? throw new ArgumentNullException(nameof(callback)),
useSynchronizationContext: false,
useExecutionContext: true);
public CancellationTokenRegistration Register(Action callback) => Register(callback, useSynchronizationContext: false);

/// <summary>
/// Registers a delegate that will be called when this
Expand All @@ -167,7 +156,7 @@ public CancellationTokenRegistration Register(Action callback) =>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) =>
Register(
s_actionToActionObjShunt,
(Action<object?>)(static obj => ((Action)obj!)()),
callback ?? throw new ArgumentNullException(nameof(callback)),
useSynchronizationContext,
useExecutionContext: true);
Expand Down

0 comments on commit 7218577

Please sign in to comment.