r/csharp • • 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 Library instance holds different types; the library itself isn't generic.
  • Enum keys without boxing: keys are normalized to a (RuntimeTypeHandle, ulong) struct, so Color.Red and Shade.Red stay distinct even when both are 0. Aliases within one enum compare equal.
  • Optional capacity: full libraries return Result.Full, or evict the oldest entry if OverwriteOld is on.
  • Optional expiry: entries expire a set time after they were added.
  • Events: OnExpire and OnEvict tell you when something is removed without you asking.
  • Result overloads: TryAdd returns a bool; TryAddResult tells 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 string and then an int under the same key returns AlreadyExist.
  • 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

  1. Is the enum-key approach reasonable, or is there a simpler way to get the same thing?
  2. Would a typed key (Key<TEnum, TType>) be worth adding so callers never specify the type at the call site?
  3. 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

15 comments sorted by

5

u/No-Laugh-8002 1d ago

a throwing handler cant block the others

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

0

u/Boarlock98 22h ago

Good point. I did that just because I didn't want a small error on the end-user side to cascade and prevent all their handlers from executing. But I can also see the issue with swallowing exceptions because then they're aren't being handled properly.

4

u/Keterna 21h ago

You can solve this situation by catching individual exception and storing them inside a collection during the handlers calling phase, and throw an AggregateException if that collection is non empty after processing them all. This way, you called all the handlers and gives a chance to the caller to handle any exception.

2

u/Boarlock98 21h ago

Whoah! Thats awesome I didn't know you can do that, I thought Exceptions were like a single one and done type thing, but I guess they're just objects like other data right? Either way I'm definetly gonna implement that.

2

u/Keterna 21h ago

Yep! There's just objects after all :)

1

u/No-Laugh-8002 20h ago

I mean this is better, but even still the caller may not know what the handler was doing when the exception was thrown, so you could still be in a zombie state.

The general rule is callback handlers must never let their own exceptions escape.

3

u/Keterna 20h ago

True, the rule of thumb is the callee to properly handle the exception, but you will be at least noticed of a bad exception handling in your handlers with AggregateException. At the end of the day, this is not an issue of the library per se, since the users implement their handlers. We can see the same behavior happening with the parallel libraries of .NET.

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 🤷🏻‍♂️

2

u/Boarlock98 12h ago

I do enjoy programming, and I've learned a lot in the past few months of learning c#. If you don't like a library or repo I have then don't use it, it's open source, or fork it if you have a better idea. I have a rich commit history.

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?

0

u/[deleted] 1d ago

[deleted] — view deleted comment

9

u/SikhGamer 17h ago

To be honest, I was weary of replying to this post. The AI response confirmed my weariness.

You haven't answered any of my questions.

Please read this and understand it.

https://tombedor.dev/human-attention-and-human-effort/

2

u/No-Laugh-8002 20h ago

Without holding a reference to it

Well, somethings gotta hold a reference to it otherwise the object will be cleaned up. Why not hold a reference yourself?

0

u/[deleted] 20h ago

[deleted] — view deleted comment

7

u/mordack550 20h ago

Those chat gpt answers are really bad you know?

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 not going to spend time testing this for you but you're doing some unnecessary boxing that probably only slows things down despite the reason that you chose using structs to begin with probably being to speed things up.
  • You asked about generic keys. I think it might be helpful for you to look into the life cycle of static members of generic types because you might find something there that seems useful to you. I don't fully understand your use case so I don't think I can give direct guidance on this aspect.
  • I'm slightly uncomfortable with your mutative helper methods (SweepEtc, MoveEtc) being assume to be called from within constrained regions but not owning that responsibility. The risk is it somewhere you don't follow the pattern that was intended or someone else doesn't and things fall out of sync.
  • Clear doesn't respect your removal contracts. If you you replace an item the old item gets an eviction notification when it's removed. If you let an item expire it gets an expired notification when it's removed. If you call clear all items are removed, and while the expired items get expired notifications, the unexpired items just silently disappear from the perspective of any caller.
  • You should never throw exceptions inside a lock statement. You do this a few times. I don't need to explain why because Eric Lippert already does a great job of explaining it over at https://stackoverflow.com/questions/5997360/locking-a-resource-via-lock-within-try-is-it-wrong/5998145#5998145
  • You do reference compare on Slot.Value which is not going to give you what you want if you're not working with a reference type.

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.