I have a question that is easily solvable in C ++, but in C # I still cannot find a good solution:
I have a function foo that should block two objects, and this function can be called with arguments in reverse order, for example:
static void foo(object o1, object o2) { lock (o1) { lock (o2) { ... } } } static void bar(object a, object b) { ThreadPool.QueueUserWorkItem(s => foo(a, b)); ThreadPool.QueueUserWorkItem(s => foo(b, a)); }
This is a book way to make a standstill. The standard way to fix this is to always lock objects in the same order. In C ++, I could compare pointers, but in "safe" C # I don't know anyone but a very ugly solution to Monitor.TryEntry (see below). Is there anything better? Note that objects are mutable, and I cannot rely on Equals , GetHashCode , IComparable .
static void foo(object o1, object o2) { const int Timeout = 1000; while (true) { if (Monitor.TryEnter(o1, Timeout)) { try { if (Monitor.TryEnter(o2, Timeout)) { try { ... return; } finally { Monitor.Exit(o2); } } } finally { Monitor.Exit(o1); } } } }
source share