O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required