When you use lock or Monitor.Enter and Monitor.Exit , these are full fences , this means that it will create a "barrier" in the Thread.MemoryBarrier() when starting or locking " Monitor.Enter " and until the end of blocking " Monitor.Exit " Thus, no operation will move before and after the lock , but note that the operations inside the lock itself can be replaced with other perspectives of the flows, but this was never a problem, since the lock guarantees mutual exclusive, therefore only one thread will execute the code inside the castle at the same time. In any case, reordering, however, will not occur in any thread, that is, with multithreading, entering the same area of ββthe code, they may not see the instructions in the same order.
I highly recommend that you learn more about the MemoryBarrier and the full and half fences in this article.
Edit: Please note that here I describe that lock is a complete fence, but not to mention the βdeadlockβ that you know, the script you describe will never happen because, as @Hans mentions, reordering will never occur for method calls, that is:
Method1(); Method2(); Method3();
It will be executed sequentially, but the instructions inside them can be changed, for example, when multithreading executes the code inside Method1() ..
source share