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:

static void Main(){    object gate = new object();    int n = 0;    var up = new Thread(() =>    {        for (int i = 0; i < 1000000; i++)            lock (gate)                n++;    });    up.Start();    for (int i = 0; i < 1000000; i++)        lock (gate)            n--; ...

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.