affiliate_link

Tuesday, March 13, 2018

Multithreading locking different ways?


The lock statement is analogous to Monitor.Enter, which does potentially block. Granted, in your example code, there shouldn't be any blocking issues; but I would wager that since lock provides blocking, it does a little more work (potentially) than TryEnter does.

1. Lock
2. Monitor.Enter
3. Monitor.TryEnter

100 iterations:
lock: 4.4 microseconds
Monitor.TryEnter: 16.1 microseconds
Monitor.Enter: 3.9 microseconds
100000 iterations:
lock: 2872.5 microseconds
Monitor.TryEnter: 5226.6 microseconds
Monitor.Enter: 2432.9 microseconds
This seriously undermines my initial guess and shows that, on my system, lock (which performs about the same as Monitor.Enter) actually drastically outperforms Monitor.TryEnter.

No comments: