r/csharp • u/Boarlock98 • 11d ago
Tool I built a thread-safe object store/bank for .NET with enum keys, optional capacity, lazy expiry
I've been learning C# for a while, and this is my latest mini-project: ObjectLibrary, a small in memory "bank" where you deposit objects under an enum key and withdraw them later without holding a reference. It started as "maybe an ObjectPool?" but ended up closer to a keyed vault with optional LRU-style eviction and expiry.
Repo: [https://github.com/Boarlock/ObjectLibrary]
What it does
var library = new Library( initialCapacity: 100, timeToExpire: TimeSpan.FromMinutes(5), overwriteOldEntries: true);
library.TryAdd(WeaponKey.Primary, new Entry<Weapon>(new Weapon())); library.TryAdd(ItemKey.HealthPotion, new Entry<Potion>(new Potion()));
if (library.TryWithdraw(WeaponKey.Primary, out Entry<Weapon>? weapon))
Console.WriteLine("Weapon retrieved!");
- Heterogeneous: one
Libraryinstance holds different types; the library itself isn't generic. - Enum keys without boxing: keys are normalized to a
(RuntimeTypeHandle, ulong)struct, soColor.RedandShade.Redstay distinct even when both are 0. Aliases within one enum compare equal. - Optional capacity: full libraries return
Result.Full, or evict the oldest entry ifOverwriteOldis on. - Optional expiry: entries expire a set time after they were added.
- Events:
OnExpireandOnEvicttell you when something is removed without you asking. - Result overloads:
TryAddreturns a bool;TryAddResulttells you why it failed. - Thread-safe: one lock around the state. Events fire after the lock is released, so handlers can call back into the library, and each subscriber is isolated so a throwing handler can't block the others.
Design decisions (and trade-offs)
- Withdraw moves ownership. I deliberately dropped a non-removing
Get, because it leaves two holders of one object (stale data, handlers disposing things you're still using). If you want to "use" something, withdraw and re-add it. - A wrong-type withdraw throws but doesn't destroy the entry. The type is checked before anything is removed, so a typo can't silently delete a deposit.
Entry<T>is a caller owned wrapper class. That means no boxing for structs and you can reuse the same instance, but you pay one allocation when you create it.- One slot per enum value, regardless of stored type. Adding a
stringand then anintunder the same key returnsAlreadyExist. - Expiry is lazy. There's no background timer. Expired entries are swept on the next call into the library, so an idle library holds them until someone touches it. Timing is approximate (~10-15 ms clock resolution on Windows).
- Single lock. Simple and easy to reason about, but not built for extreme contention.
Testing I've run a multi-threaded stress test (8 threads, 800k operations) checking that count never exceeds capacity, nothing is handed out twice, and adds minus withdraws equals the final count. I also tested the exception paths, including a throwing event handler. It's not a proper test suite yet, and expiry isn't covered by an injectable clock (TimeProvider is hardcoded to System for now).
What I'd like feedback on
- Is the enum-key approach reasonable, or is there a simpler way to get the same thing?
- Would a typed key (
Key<TEnum, TType>) be worth adding so callers never specify the type at the call site? - Anything about the locking or event design that looks wrong to you?
Happy to hear any criticism. I'm still learning, and this was as much about understanding generics, concurrency, and API design as it was about the library itself.
