I have a pool of "accounts". Each one can only be used by one thread at a time. So at first I thought that a simple lock should suffice. But it turned out that that won't work easily.
The only idea this would work would be to use Monitor.TryEnter with an timeout of 0 and then keep looping over the objects forever until at some point I successfully lock onto an account, then use it.
This is obviously not very easy on the computers resources and generally bad style.
My next Idea was to give each object a queue of actions like this List<Action<Account> queue but somehow that doesn't seem very elegant either.
The actions I do on the accounts are async Task as well so that makes everything even more complex. (Having to use Nito.AsyncEx instead of normal lock())
Usually I do not care about what account I work with as long as my action is executed. So I work with the first account that's available at the moment. But sometimes I even want to operate on a specific account as well.
How should I design my "AccountPool" so I can easily have methods like ExecuteOnFirstUnusedAccount(Action<Account> action) and ExecuteOnSpecificAccount(Func<Account,bool> filter, Action<Account> action) ?
edit: One possible solution I just thought of would be the following.
Each account has its own Task (or Thread, doesn't matter). Then there's a single (global) BlockingCollection<Action<Account>> and each of those Tasks then calls .Take() on the collection.
The problem with that: When I need to have one specific Account execute some action that's not possible anymore since they all wait for the blocking collection.