Clear hoisted locals when disposing iterator and async-iterator state machines #75908
+1,505
−217
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.
Fixes #75666
Background
We already have logic to clear unmanaged hoisted locals when we exit scopes. But that logic has a number of limitations:
foreach (var i in coll) { break; }
)So the current design only works for nested locals on normal exit from their scope.
Change
This PR clears the hoisted fields for all the locals (top-level and nested) in the part of the code that handles disposal: in
Dispose
method for iterators and at the end ofMoveNext
for async-iterators.There is no need to add such clearing for async state machines, as it is non-trivial for a user to get a direct reference to those.
The proposed design fixes scenarios 1, 2, 3, and most of 4 (a throw during disposal still results in uncleared state).
This remains "best effort", as we don't want to add the overhead of an additional
try
/finally
to handle that last scenario.Look at the diff between commit 1 (baseline) and commit 2 (code change) to see the expectedOutput and IL changes.