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 the same lock is released as the one that was acquired. If the lock expression references a field or calls a method, ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.