Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,8 @@ public Task CancelAsync()
}, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
}

_state = States.NotifyingCompleteState;
}

// As with Cancel, CancelAsync returns immediately if cancellation has already been requested
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1767,35 +1767,56 @@ public static void CancellationTokenSource_Ctor_ZeroTimeout(bool timeSpan)
}
}

[Fact]
public static void CancellationTokenSource_CancelAsync_NoRegistrations_CallbackCompletesImmediately()
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public static void CancellationTokenSource_CancelAsync_NoRegistrations_CallbackCompletesImmediately(bool unregisterCallback, bool createWaitHandleBeforeCancellation)
{
var cts = new CancellationTokenSource();
Assert.True(cts.CancelAsync().IsCompletedSuccessfully);
Assert.True(cts.IsCancellationRequested);
using var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
if (unregisterCallback)
{
token.Register(() => { }).Dispose();
}

cts = new CancellationTokenSource();
cts.Token.Register(() => { }).Dispose();
using WaitHandle handle = createWaitHandleBeforeCancellation ? token.WaitHandle : null;
Assert.True(cts.CancelAsync().IsCompletedSuccessfully);
Assert.True(cts.IsCancellationRequested);
Assert.False(cts.TryReset());

using WaitHandle canceledHandle = token.WaitHandle;
Assert.True(canceledHandle.WaitOne(0));
Assert.False(canceledHandle.SafeWaitHandle.IsClosed);

cts.Dispose();
Assert.True(canceledHandle.SafeWaitHandle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => token.WaitHandle);
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
public static async Task CancellationTokenSource_CancelAsync_CallbacksInvokedAsynchronously()
{
var cts = new CancellationTokenSource();
using var cts = new CancellationTokenSource();
using WaitHandle handle = cts.Token.WaitHandle;

var mres = new ManualResetEventSlim();
using var mres = new ManualResetEventSlim();
cts.Token.Register(mres.Wait);

Task t = cts.CancelAsync();
Assert.False(t.IsCompleted);
Assert.True(cts.IsCancellationRequested);

Assert.True(cts.CancelAsync().IsCompletedSuccessfully); // secondary call completes immediately
Assert.False(handle.SafeWaitHandle.IsClosed);
Assert.True(handle.WaitOne(0));

mres.Set();
await t;

cts.Dispose();
Assert.True(handle.SafeWaitHandle.IsClosed);
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
Expand Down
Loading