Make Async.RunSynchronously more conservative about using current thread (reverting part of 11142) #12638
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.
As described in #12637 (comment), part of #11142 created a problematic change in behaviour about when
Async.RunSynchronouslyuses the current thread. Using the current thread is godo for performance and stacks but can cause deadlock if the current thread is relied on to process part of the async computation.Prior to Await completed Tasks on the same thread. #11142 the current thread was used if
SynchronizationContextis null (and no timeout specified)After Await completed Tasks on the same thread. #11142 the current thread is used if
Thread.CurrentThread.IsThreadPoolThreadis true (and no timeout specified).This change was not conservative - we now start on the current thread more often than we did before, specifically when we have non-null
SynchronizationContext, yetCurrentThread.IsThreadPoolThreadis true.The idea of #11142 was not bad - it tries to make sure the computation always runs in the thread pool. However sometimes thread-pool threads have non-null
SynchronizationContext.Current, and this is an indication that starting the async computation on the current thread is not acceptable.As a conservative fix, we clarify the spec of
RunSynchronouslyas follows:This PR adjusts the code to match that.
Testing
Running without first adjusting tests to see if our existing tests clarify this.