Improved threadsafety for FileIndexTable.FileToIndex #18137
Merged
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 is a slight improvement to the threadsafety of the FileIndexTable.FileToIndex property.
The issue with the original code was when two threads were racing to add a file, if each thread has the same value for filePath and it hadn't already been added, the code would queue behind the lock and add the file twice with different ids.
The original fix to the code was to grab a lock whenever it was likely to add an index, this nicely synchronized the query whether the item was already in the dictionary.
This fix goes back to the original smaller lock just around the specific code path that adds the item. Before adding an item, it rechecks within the lock that the item is in the list. If it isn't it adds it. Otherwise it bails.
Note:
fileToIndexTable is a ConcurrentDictionary<string, int> therefore threadsafe and efficient when accessing.
we synchronize access on the fileToIndexTable syncblock.
/cc @T-Gro , @vzarytovskii , @Martin521