Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race condition with cancellation tokens in Read/Flush operations #59090

Merged
merged 4 commits into from
Sep 15, 2021
Merged
Changes from 2 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 @@ -47,16 +47,29 @@ public void BeginOperation(CancellationToken cancellationToken, Action<object?>
{
cancellationToken.ThrowIfCancellationRequested();

_awaitableState |= AwaitableState.Running;

// Don't register if already completed, we would immediately unregistered in ObserveCancellation
if (cancellationToken.CanBeCanceled && !IsCompleted)
{
var previousAwaitableState = _awaitableState;
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved

_cancellationTokenRegistration = cancellationToken.UnsafeRegister(callback, state);
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

// If we get back the default CancellationTokenRegistration then it means the
// callback synchronously and we can throw inline. This is safe because we haven't changed
// the state of the awaitable as yet.
if (_cancellationTokenRegistration == default(CancellationTokenRegistration))
{
Debug.Assert(previousAwaitableState == _awaitableState, "The awaitable state changed!");
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

cancellationToken.ThrowIfCancellationRequested();
pakrym marked this conversation as resolved.
Show resolved Hide resolved
}

#if (NETSTANDARD2_0 || NETFRAMEWORK)
_cancellationToken = cancellationToken;
#endif
_cancellationTokenRegistration = cancellationToken.UnsafeRegister(callback, state);
}

_awaitableState |= AwaitableState.Running;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down