Intermezzo: Code Generation for Lock

In the last release of the C# language, code generation for the lock statement has been changed due to a truly fascinating story in compiler development land. Consider the following fragment:

lock (expression)    embedded-statement

Before version 4.0, this lock statement translated into the following fragment:

var __lockExpression = expression;Monitor.Enter(__lockExpression);try{    embedded-statement}finally{    Monitor.Exit(__lockExpression);}

It turns out, the preceding code is plagued with some very subtle issues. For starters, the lock object is stored in a temporary local variable to ensure that the same lock is released as the one that was acquired. If the lock expression references a field or calls ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.