Guard the counter value caches with a lock

Merged
SI
3mo ago
+115-33

Each Counter value cache (Guid, DateTime, DateTimeOffset, Date, Time, numeric id) is a plain Dictionary written through Extensions.GetOrAdd, while the number behind the name came from Interlocked.Increment. The mix reads as thread safe but is not: the interlocked part guards only the counter, not the dictionary that stores the result.

Counter.Current is public and reachable from user code, so parallel work inside a single test hits it concurrently. On main that reliably produces:

System.InvalidOperationException : Operations that change non-concurrent collections
must have exclusive access. A concurrent update was performed on this collection and
corrupted its state.

and sometimes Destination array was not long enough from a resize racing a read.

All the caches now share one lock. ConcurrentDictionary would have been the smaller diff, but its GetOrAdd can run the factory more than once under contention, which would burn counter numbers and hand out a name that is then discarded. A lock keeps the numbering tight, and it also covers the numeric id path, which mutates two dictionaries (the per entity cache and the per entity counter) that no single concurrent collection would make atomic together.

With the caches locked the interlocked increments are redundant, so they become plain increments, and the Build* methods are commented as being called under the lock.

CounterConcurrencyTests drives 500 distinct values through Parallel.ForEach for guids and numeric ids, asserting one name per input and that each input keeps its name. Both fail on main — 3 runs out of 3 while checking.

Verify.Tests passes on net11.0 (1301) and net48 (1222); StaticSettingsTests and ApplyScrubbersTests pass.