O'Reilly logo

C# 4.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

Monitors and the lock Keyword

One fundamental synchronization primitive is the concept of a monitor, as exposed through the Monitor class in System.Threading. In most cases, the use of a monitor is hidden because of the use of the lock keyword in C#, which leverages this primitive under the covers.

For our running example of a shared counter, we can make the following changes to prevent the two threads from updating the state simultaneously:

image

No matter how many times you run this code, the outcome should always be zero (as we expected in the first place). The way this works is by the monitor’s guarantee that no two threads can be operating under ...

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