This code is buggy.
See the line:
if (Monitor.TryEnter(po1) && Monitor.TryEnter(po2))
Imagine that the lock to
, but for
It will not return, and later will lock
So, when unlocking, it will unlock the wrong number of times.
I really think that if you always lock in the same order with conventional lock:
or if you get rid of one of the locks, you will have better code.
If that's not the case, I think a better implementation will be like this:
Receive an array of objects to lock (so, it can have more than two).
It will create an array of bools of the same size.
At each try, it will only try to lock if lock was not already taken for the given index (using that boolean array).
When locking, it will use
TryEnter(1, ref locksTaken[lockIndex]);
And, if an exception is thrown, it will unlock all already taken locks.
But to be honest, even if this approach never deadlocks, it will timeout to often by "dead-lock" conditions... it is better to enforce lock ordering.
I started to program computers when I was 11 years old, as a hobbist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.
At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do they work easier, faster and with less errors.
Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: firstname.lastname@example.org
Codeproject MVP 2012
Microsoft MVP 2013