Force the OneTimeTearDown to be executed on the current thread if STA #4004
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.
This aims to be a workaround for #3961
When both
SingleThreaded
andParallizable
attributes are attached to the test fixture,SingleThreadedAttribute.ApplyToContext
may be executed later than expected (even after all test methods in the test fixtures are executed), so it leads to the following result:The parent context still has
IsSingleThreaded
false, and all the test methods are executed on this context: (targetApartment
andcurrentApartment
are bothUnknown
, inWorkItem.Execute
), soWorkItem.RunOnCurrentThread
is always called.Then, when the
OneTimeTearDown
of test fixture is executed, a newOneTimeTearDownWorkItem
is created based on the current work item (seeCompositeWorkItem.OnAllChildItemsCompleted
), which inherits the parentExecutionStrategy
. At that time, since theContext.IsSingleThreaded
may still haven't been set to true, theExecutionStrategy
will beParallel
.At this time, not sure about the call stack,
SingleThreadedAttribute.ApplyToContext
is called andIsSingleThreaded
set to true.When the one time tear down work item is actually executed, though
Context.IsSingleThreaded
is now true, but theParallelExecutionStrategy
is already set in step 2, so it will still fall into theParallelExecutionStrategy.Parallel
branch and executed by a parallel queue, which may happen on another thread (seeParallelWorkItemDispatcher.Dispatch
).The PR adds a workaround, when it's going to execute the work item, double-check if
Context.IsSingleThreaded
is set to true, and if so, force it to run on the current thread.The clean fix should be investiage why step 3 is delayed but that's beyond my ability. Thanks.