Fix race condition causing duplicate MonitoredItems in concurrent CreateItemsAsync calls #3399
+119
−18
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.
Proposed changes
Multiple threads calling
CreateItemsAsyncconcurrently could create duplicate MonitoredItems on the server. The issue occurs because items are marked as created only after receiving the server response, allowing other threads to include the same items in separate create requests during the network round-trip.Solution: Add internal
Creatingflag to track items with pending create requests.Key Changes
Creatingproperty set before releasing lock, cleared after responseCreated || Creatingto prevent concurrent requests for same itemCreatingflag on exceptions to handle error pathsConcurrentCreateItemsNoDuplicatesverifying 3 concurrent calls don't create duplicatesExample
Before fix - race condition:
After fix - prevented by Creating flag:
Related Issues
Fixes #2731
Types of changes
Checklist
Further comments
The fix is minimal and surgical - a single boolean flag prevents the race window. The
Creatingflag follows the same internal visibility pattern as other status tracking fields inMonitoredItemStatus. Exception handling ensures the flag is cleared even on network failures or validation errors, preventing items from becoming permanently stuck in the "creating" state.Original prompt
Subscription.CreateItems#2031💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.