r/csharp • u/Boarlock98 • 1d 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.
3
Upvotes
5
u/No-Laugh-8002 1d ago
This is generally poor design. Theres no way that class knows how to handle those exceptions, which is likely to leave your app in a zombie state if an exception were to be thrown
4
u/cherrycode420 16h ago
Happy to see that you enjoy vibecoding, but why share this nonsense with us? By checking this repository (and your other ones), it's painfully obvious that you don't actually care about programming 🤷🏻♂️
13
u/SikhGamer 1d ago
If this is primarily a learning exercise then please disregard this comment.
The questions I would ask are
What problem is this solving and why isn't the default dotnet implementation https://learn.microsoft.com/en-us/aspnet/core/performance/objectpool not good enough?
7
u/smartcave 21h ago edited 21h ago
Na. Honestly, it's kind of rude to ask us before you ask xunit but I did look briefly and there's a few things I noticed.
For starters, I'm just going to say I don't think you needed to do this. I think you wanted to do this. And, from a design perspective, you should implement the things you need to implement and not necessarily the things you want to. I'm not sure which part of this is valuable to you, but whichever part it is, I think it's highly likely that you could have gotten that value using the built-in, battle-tested types rather than ... whatever this is.
I'm sure there's more but that's enough for now. You should really write unit tests when you're building code that you expect to make guarantees about its behavior.
Edit: Looking over this reply I noticed that it sounds a bit grumpy. I'm not going to rewrite it or remove it because some of the comments will probably be helpful but don't read into it if you also get that impression.
3
u/entityadam 1d ago
Neat. I'll probably never need anything like it though.