-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Fixes some theoretical races and retentions in AsyncOperation and ManualResetValueTaskSource #127256
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
Open
VSadov
wants to merge
5
commits into
dotnet:main
Choose a base branch
from
VSadov:vtsRaces
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+111
−74
Open
Fixes some theoretical races and retentions in AsyncOperation and ManualResetValueTaskSource #127256
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -139,7 +139,7 @@ private CancellationToken CancellationToken | |
| #endif | ||
|
|
||
| /// <summary>Gets whether the operation has completed.</summary> | ||
| internal bool IsCompleted => ReferenceEquals(_continuation, s_completedSentinel); | ||
| internal bool IsCompleted => ReferenceEquals(Volatile.Read(ref _continuation), s_completedSentinel); | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Performing an ordinary read could allow prefetching _error and we could end up assuming that a failed/cancelled operation actually cleanly completed. |
||
|
|
||
| /// <summary>Completes the operation with a failed state and the specified error.</summary> | ||
| /// <param name="exception">The error.</param> | ||
|
|
@@ -267,12 +267,13 @@ private void SetCompletionAndInvokeContinuation() | |
| Debug.Assert(_continuation is not null); | ||
|
|
||
| object? ctx = _capturedContext; | ||
| _capturedContext = null; | ||
|
|
||
| ExecutionContext? ec = | ||
| ctx is null ? null : | ||
| ctx as ExecutionContext ?? | ||
| (ctx as CapturedSchedulerAndExecutionContext)?._executionContext; | ||
|
|
||
| _capturedContext = null; | ||
| if (ec is null) | ||
| { | ||
| Action<object?> c = _continuation!; | ||
|
|
@@ -359,43 +360,52 @@ public void OnCompleted(Action<object?> continuation, object? state, short token | |
| // inside the awaiter's OnCompleted method and we want to avoid possible stack dives, we must invoke | ||
| // the continuation asynchronously rather than synchronously. | ||
| Action<object?>? prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); | ||
| if (prevContinuation is not null) | ||
| if (prevContinuation is null) | ||
| { | ||
| // If the set failed because there's already a delegate in _continuation, but that delegate is | ||
| // something other than s_completedSentinel, something went wrong, which should only happen if | ||
| // the instance was erroneously used, likely to hook up multiple continuations. | ||
| Debug.Assert(IsCompleted, $"Expected IsCompleted"); | ||
| if (!ReferenceEquals(prevContinuation, s_completedSentinel)) | ||
| { | ||
| Debug.Assert(prevContinuation != s_availableSentinel, "Continuation was the available sentinel."); | ||
| ThrowMultipleContinuations(); | ||
| } | ||
| // Operation hadn't already completed, so we're done. The continuation will be | ||
| // invoked when SetResult/Exception is called at some later point. | ||
| return; | ||
| } | ||
|
|
||
| // Queue the continuation. We always queue here, even if !RunContinuationsAsynchronously, in order | ||
| // to avoid stack diving; this path happens in the rare race when we're setting up to await and the | ||
| // object is completed after the awaiter.IsCompleted but before the awaiter.OnCompleted. | ||
| if (_capturedContext is null) | ||
| { | ||
| ChannelUtilities.UnsafeQueueUserWorkItem(continuation, state); | ||
| } | ||
| else if (sc is not null) | ||
| { | ||
| sc.Post(static s => | ||
| { | ||
| var t = (KeyValuePair<Action<object?>, object?>)s!; | ||
| t.Key(t.Value); | ||
| }, new KeyValuePair<Action<object?>, object?>(continuation, state)); | ||
| } | ||
| else if (ts is not null) | ||
| { | ||
| Debug.Assert(ts is not null); | ||
| Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); | ||
| } | ||
| else | ||
| // Queue the continuation. We always queue here, even if !RunContinuationsAsynchronously, in order | ||
| // to avoid stack diving; this path happens in the rare race when we're setting up to await and the | ||
| // object is completed after the awaiter.IsCompleted but before the awaiter.OnCompleted. | ||
|
|
||
| // We no longer need the stored values as we will be passing the state when queuing directly | ||
| _continuationState = null; | ||
| object? capturedContext = _capturedContext; | ||
| _capturedContext = null; | ||
|
|
||
| // If the set failed because there's already a delegate in _continuation, but that delegate is | ||
| // something other than the completion sentinel, something went wrong, which should only happen if | ||
| // the instance was erroneously used, likely to hook up multiple continuations. | ||
| Debug.Assert(prevContinuation != s_availableSentinel, "Continuation was the available sentinel."); | ||
| Debug.Assert(IsCompleted, $"Expected IsCompleted"); | ||
| if (!ReferenceEquals(prevContinuation, s_completedSentinel)) | ||
| { | ||
| ThrowMultipleContinuations(); | ||
| } | ||
|
|
||
| if (capturedContext is null) | ||
| { | ||
| ChannelUtilities.UnsafeQueueUserWorkItem(continuation, state); | ||
| } | ||
| else if (sc is not null) | ||
| { | ||
| sc.Post(static s => | ||
| { | ||
| Debug.Assert(_capturedContext is ExecutionContext); | ||
| ChannelUtilities.QueueUserWorkItem(continuation, state); | ||
| } | ||
| var t = (KeyValuePair<Action<object?>, object?>)s!; | ||
| t.Key(t.Value); | ||
| }, new KeyValuePair<Action<object?>, object?>(continuation, state)); | ||
| } | ||
| else if (ts is not null) | ||
| { | ||
| Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); | ||
| } | ||
| else | ||
| { | ||
| Debug.Assert(capturedContext is ExecutionContext); | ||
| ChannelUtilities.QueueUserWorkItem(continuation, state); | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -470,11 +480,22 @@ void IValueTaskSource.GetResult(short token) | |
|
|
||
| if (_pooled) | ||
| { | ||
| Volatile.Write(ref _continuation, s_availableSentinel); // only after fetching all needed data | ||
| ClearRetainedState(); | ||
| // enable reuse only after fetching all needed data | ||
| Volatile.Write(ref _continuation, s_availableSentinel); | ||
| } | ||
|
|
||
| error?.Throw(); | ||
| } | ||
|
|
||
| internal virtual void ClearRetainedState() | ||
| { | ||
| _error = null; | ||
|
VSadov marked this conversation as resolved.
|
||
| Debug.Assert((object?)Next == null); | ||
| Debug.Assert((object?)Previous == null); | ||
| Debug.Assert(_continuationState == null); | ||
| Debug.Assert(_capturedContext == null); | ||
| } | ||
|
VSadov marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /// <summary>Represents an asynchronous operation with a result on a channel.</summary> | ||
|
|
@@ -515,24 +536,28 @@ public TResult GetResult(short token) | |
|
|
||
| if (_pooled) | ||
| { | ||
| Volatile.Write(ref _continuation, s_availableSentinel); // only after fetching all needed data | ||
| ClearRetainedState(); | ||
| // enable reuse only after fetching all needed data | ||
| Volatile.Write(ref _continuation, s_availableSentinel); | ||
| } | ||
|
|
||
| error?.Throw(); | ||
| return result!; | ||
| } | ||
|
|
||
| internal override void ClearRetainedState() | ||
| { | ||
| base.ClearRetainedState(); | ||
| _result = default; | ||
| } | ||
|
|
||
| /// <summary>Attempts to take ownership of the pooled instance.</summary> | ||
| /// <returns>true if the instance is now owned by the caller, in which case its state has been reset; otherwise, false.</returns> | ||
| public bool TryOwnAndReset() | ||
| { | ||
| Debug.Assert(_pooled, "Should only be used for pooled objects"); | ||
| if (ReferenceEquals(Interlocked.CompareExchange(ref _continuation, null, s_availableSentinel), s_availableSentinel)) | ||
| { | ||
| _continuationState = null; | ||
| _result = default; | ||
| _error = null; | ||
| _capturedContext = null; | ||
| return true; | ||
|
VSadov marked this conversation as resolved.
|
||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.