Fix thread-safety bug in QueryGenerator caused by static mutable field#116
Open
penspanic wants to merge 1 commit intogenaray:masterfrom
Open
Fix thread-safety bug in QueryGenerator caused by static mutable field#116penspanic wants to merge 1 commit intogenaray:masterfrom
penspanic wants to merge 1 commit intogenaray:masterfrom
Conversation
The _classToMethods dictionary was declared as a static field, causing "Collection was modified; enumeration operation may not execute" errors during parallel builds when multiple compilations invoke the generator concurrently. Replace the static field with a local variable in Generate() and pass it as a parameter to AddMethodToClass(). Add a concurrency test that reproduces the race condition with parallel generator invocations.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
QueryGeneratoruses astatic Dictionary<ISymbol, List<IMethodSymbol>> _classToMethodsfield that is shared across all concurrent generator invocations. During parallel builds (e.g. multiple projects referencing the generator, or multi-targeting), this causes intermittent:The error occurs because one thread enumerates
_classToMethodsin theforeachloop while another thread reassigns or mutates it in a concurrentGenerate()call.Fix
Remove the static field and replace it with a local variable inside
Generate(), passed as a parameter toAddMethodToClass(). Since the dictionary is already re-created at the start of everyGenerate()call, there is no need for it to persist across calls.Test
Added
ConcurrencyTestthat runs 8 parallel generator invocations with[Repeat(10)]. Before the fix, this fails 100% of the time. After the fix, it passes 100%.