Use a dictionary that provides different lock objects for different arguments. Set up the dictionary when you instantiate the base object (or statically, if applicable):
var locks = new Dictionary<int, object>() { {1, new Object()}, {2, new Object()}, β¦ };
And then use it inside your method:
void Foo(int bar) { lock (locks[bar]) { β¦ } }
I would not say that this solution is erratic, on the contrary: the provision of shallow literacy locks is commendable, and since value type locks do not work in .NET, having a mapping is an obvious solution.
Be careful: the above only works until the dictionary is changed and read at the same time. Therefore, it is best to use a read-only dictionary after setting it up.
Konrad Rudolph
source share