dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.36k stars 4.74k forks source link

Potential inconsistent MemoryCache stats #108333

Open verdie-g opened 1 month ago

verdie-g commented 1 month ago

Description

The stats provided by MemoryCache might randomly decrease for a short time when a thread dies.

That problem did not occur to me in production but I would like to use a similar pattern in my library, so I would be interested to double check that the pattern is valid.

Reproduction Steps

  1. A thread dies
  2. The thread and thread locals get collected
  3. The WeakReference in MemoryCache._allStats should now point to null
  4. During that time, the thread local stats is not referenced by the _allStats list anymore and is not in the dead threads accumulator either
  5. The Stats finalizer is called and the value of the thread counter is now added to the accumulators.

Expected behavior

The MemoryCache stats should always increase and never decrease.

Actual behavior

The MemoryCache stats might decrease in some rare case.

dotnet-policy-service[bot] commented 1 month ago

Tagging subscribers to this area: @dotnet/area-extensions-caching See info in area-owners.md if you want to be subscribed.