I would like to use exactly one of a set of resources from a multi-threaded C# application. These resources are not thread-safe, so some lock or mutex must be for them. How should I do it?
I would like to get something like the following pseudo code:
lockAny([obj1, obj2, obj3]) {
achievedLock = getAchievedLock(); // returns e. g. obj2
myResource = getResourceForLock(achievedLock); // some function written by me, looks up the resource belonging to the particular lock
myResource.DoSomething();
}
CodePudding user response:
The best way to do this is with some sort of pooling. A pool object can attempt to ensure that only 1 thing has a reference at a time (but .NET can't guarantee that like Rust).
.NET has recently added Microsoft.Extensions.ObjectPool<T>
. You can configure how it creates the items. Some examples here.