lock vs. MethodImplOptions.Synchronized [Kit George]

A BCL Website customer (Michael) recently asked:

Is there any difference in the jitted code between using the Attribute System.Runtime.CompilerServices.MethodImplAttribute( MethodImplOptions.Synchronized ) and using a lock(this) {...} in the method body? The IL code is different. What you suggest to use for synchronizing complete methods?

Michael, both options are functionally equivalent. However, for most cases we recommend neither of them, for the following reasons.

We strongly discourage the use of lock(this). Since other, completely unrelated code can choose to lock on that object as well, you could find yourself trying to debug a hard-to-find deadlock or throughput problem. Instead, either lock on the object you’re sharing across threads (assuming you know its code never tries to lock on it for unrelated reasons), or create a private dummy object to lock on.

A given piece of IL may generate different code from release to release, or between JIT and NGEN. Anything we tell you now—or you find out by disassembly—might not be valid in the next release.