Table of Contents

ShardedDictionary

Description

A thread-safe generic dictionary that distributes keys across 4 shards to reduce lock contention and improve throughput under concurrent load.

Features

  • Sharded storage: 4 internal ConcurrentDictionary shards — keys distributed by hash
  • Auto-clear: each shard clears itself when it reaches capacity — no manual management needed
  • Cache helper: Cache(key, getItem) returns existing value or creates and stores a new one
  • Standard API: TryAdd, TryGetValue, TryRemove, ContainsKey, TryUpdate, Clear, Count, Keys

Behavior

Shard is selected by key.GetHashCode() & 3 — O(1) shard lookup.

When a shard exceeds its capacity (maxItemCount / 4), the entire shard is cleared before adding the new item. This is a hard clear — not LRU, not eviction — all items in that shard are lost. Default total capacity is 100,000 items (25,000 per shard).

Cache() is a get-or-create helper — if key exists returns it, otherwise calls getItem(), stores and returns result. Used extensively inside the framework for reflection caching.

Caveats

  • Shard clear is all-or-nothing — when capacity is hit, entire shard is wiped, not just oldest entries
  • Count property iterates all 4 shards — slightly expensive, avoid in tight loops
  • Keys property yields across all shards — not a snapshot, concurrent modifications may affect iteration
  • ClearLock is a static object — shared across ALL ShardedDictionary instances, potential contention
Tip

Use Cache() instead of TryGetValue + TryAdd — it handles the get-or-create pattern atomically per shard.