Don't free the apartment_context while we are still using it #691
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.
The apartment-switching function
resume_apartment_synctakes a context and a coroutine handle and resumes the coroutine in that context. The context is taken by reference, which is a problem if the coroutine resumption is going to destruct the context: We destruct the context while its call toContextCallbackis still active.The awaiter for
IAsync*captures the context into the completion handler, which is a separate object from the coroutine, so resuming the coroutine will not destruct the context.However, the awaiter for
apartment_contextuses the context stored directly inside theapartment_contextitself, which could be destructed as part of resumption:The first thing the coroutine does on resumption from
co_await saveis destruct theapartment_context, which releases thecontextwhileContextCallbackis still active.Fix by copying the context and resuming the copy. That way, the context isn't destructed until after
resume_context_synchas definitely returned fromContextCallback.We can't
std::movethe context out of theapartment_contextbecause that would prevent an apartment context from beingco_awaited more than once.