Introduction to Lock Threading

Introduction to Transaction Locking

Introduction to Atomicity

Consider the following analogy. In a department store (a store that sells clothes), a customer selects and brings ten (or more) items to the cashier. The cashier is using a cashing machine (also called point of sale or POS) to process the customer's orders but there is also another cashing machine available but nobody is using it at this time. The cashier starts processing the customer's purchase. Another customer comes from somewhere and says that he just has a simple question for the cashier. The cashier stops the processing she was doing in order to answer the other customer's question. After answering the question, the clerk continues serving the first customer. A few seconds later, a manager interrupts the cashier asking why there so many clothes on the floor throughout the store. The cashier stops what she was doing and thinks about how to answer the manager, but the manager starts talking about something else. To be polite and respectful, the cashier continues listening and seems interested in what the manager is saying. The manager leaves and the clerk resumes what she was doing. Another customer comes from nowhere, asks the waiting customer if he doesn't mind (mind what? Who knows?). The new customer asks the previous customer if he (the new customer) can move ahead because he has only two items and he left his car parked outside in a towing area. The old customer says he doesn't mind. The new customer walks to the cashier who now has to think about helping the new customer while the previous customer is waiting. The clerk things: (*) should she ask the new customer to wait until she has completed the first customer's order? (*) Should she cancel the previous customer order in order to process the new one? (*) Should she use another machine to process the order of the new customer in order to reduce confusion? etc. Let's consider that the cashier serves the new customer and now she must come back to completing the order of the previous customer. What if the previous customer is now upset and starts talking aloud (yelling, cursing, etc). What if the cashier doesn't remember what clothes she had rang already and what others are left? What if the cashier was going to give a discount to the previous customer but now she doesn't remember what type of discount she was going to apply? What if, for some unpredictable reason, the machine has stopped working, in which case the cashier is wondering whether the previous transactions, or some transactions, had been saved, etc.

In the same way, there are many transactions going on inside the computer, and there are many threads running at the same time. The threads must share resources (such as the memory (RAM), the media (hard drives, DVD/Blu-ray players), ports (USB, Wi-Fi, etc). In fact, threads also compete for (the availability of) resources. As a result, threads interrupt each other. Just like in real life where some people drive faster because they think they are more in a hurry than others, some threads want to complete their jobs faster or regardless of what other threads need. Just like in real life, these situations create problems, conflicts, misunderstandings, etc. Both the computer processor and the operating system try to deal with various types of these problems. You too as a programmer can intervene to solve them. One way to address these issues is referred to as atomicity.

Atomicity is the ability to complete a transaction in an all-or-nothing scenario. It means that when a transaction starts, it must be completed. If anything interrupts the transaction before it ends, if anything prevents the transaction from completing, the whole transaction is cancelled as if it never took place. Both the C# language and the .NET Framework provide the means to deal with atomicity.

Locking a Transaction

Locking a transaction consists of isolating its area of work so that nothing else in the flow of the program would be dealt with until that area of work is complete. The use of a lock in C# is done using the lock keyword in a formula as follows:

lock(holder)
{
    // What to do
}

You start with the lock keyword that appears as when calling a method. The job to do, which we referred to as a transaction, is between curly brackets { and }. That code area is called a critical section. Just like in the real world where you must first purchase a lock, in C# you must have a key. You have various options. You can use a string as a key and pass that string as the argument of the lock keyword. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise
{
    Form frmExercise = new Form();

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        frmExercise.Text = "Exercise";
        frmExercise.ClientSize = new System.Drawing.Size(500, 370);
        frmExercise.StartPosition = FormStartPosition.CenterScreen;

        frmExercise.Paint += (sender, e) =>
        {
            lock("Eye")
            {
                Point pt1 = new Point( 50, 100);
                Point pt2 = new Point(150,  50);
                Point pt3 = new Point(450,  50);
                Point pt4 = new Point(350, 100);
                Point pt5 = new Point(450, 250);
                Point pt6 = new Point(350, 300);

                Point[] ptsTopFace = new Point[]{ pt1, pt2, pt3, pt4 };
                Point[] ptsRightFace = new Point[]{ pt4, pt3, pt5, pt6 };

                e.Graphics.FillRectangle(Brushes.Maroon, new Rectangle(pt1.X, pt1.Y, 300, 200));
                e.Graphics.FillPolygon(Brushes.Orange, ptsTopFace);
                e.Graphics.FillPolygon(Brushes.Bisque, ptsRightFace);
            }
        };

        Application.Run(frmExercise);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();

        return 0;
    }
}

Introduction to Atomicity

Actually, the key must be a reference type. This means that you must use an object that is of the object type or a class (not a structure type, and remember that any class you create in C# is directly or indirectly derived from the Object class). To provide this object, you can first declare a variable of the desired type. If you declare the variable, you must initialize it using any constructor of that class. The name of the variable follows the rules of names of variables in C#. You will pass that variable to lock(). Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise
{
    Form frmExercise = new Form();

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        object locker = new object();

        frmExercise.Text = "Transactions";
        frmExercise.ClientSize = new System.Drawing.Size(450, 320);
        frmExercise.StartPosition = FormStartPosition.CenterScreen;

        frmExercise.Paint += (sender, e) =>
        {
            lock(locker)
            {
                Point pt1 = new Point( 50,  62);
                Point pt2 = new Point(188, 246);
                Point pt3 = new Point(380, 192);
                Point pt4 = new Point(250,  48);
                Point[] pts = { pt1, pt2, pt3, pt4 };
            
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt1.X - 3, pt1.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt2.X - 3, pt2.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt3.X - 3, pt3.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt4.X - 3, pt4.Y - 3, 6, 6));

                e.Graphics.DrawCurve(Pens.Blue, pts);
            }
        };

        Application.Run(frmExercise);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();

        return 0;
    }
}

Introduction to Atomicity

In most cases, you will not use the key other than passing it to lock(). Based on this, you don't have to first declare a variable. You can pass the new keyword and the constructor in the parentheses of lock(). Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise
{
    Form frmExercise = new Form();

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        frmExercise.Text = "Exercise";
        frmExercise.ClientSize = new System.Drawing.Size(550, 350);
        frmExercise.StartPosition = FormStartPosition.CenterScreen;

        frmExercise.Paint += (sender, e) =>
        {
            lock(new object())
            {
                Point pt1 = new Point(40, 42);
                Point pt2 = new Point(188, 246);
                Point pt3 = new Point(484, 192);
                Point pt4 = new Point(350, 48);
                Point[] pts = { pt1, pt2, pt3, pt4 };
                Pen penCurrent = new Pen(Color.DarkGreen);
                e.Graphics.DrawCurve(penCurrent, pts, 2.15F);

                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt1.X - 3, pt1.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt2.X - 3, pt2.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt3.X - 3, pt3.Y - 3, 6, 6));
                e.Graphics.FillRectangle(Brushes.Red, new Rectangle(pt4.X - 3, pt4.Y - 3, 6, 6));
            }
        };

        Application.Run(frmExercise);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();

        return 0;
    }
}

Introduction to Atomicity

When you use a lock in C#, no thread should (or can) interrupt the transaction(s) of that lock; that is, everything in its curly brackets must complete. Any thread that reaches that section must wait.

In the real world, you can use only one lock per item such as per house or suitcase, etc. In your application, you can use the same lock in different critical sections (such as in different methods or inside the same method). This is said that the sections (or methods) share the same lock. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

public class Exercise : Form
{
    Timer tmrStars;

    Point[] ptStars = new Point[100];

    public Exercise()
    {
        InitializeComponent();

        SetStyle(ControlStyles.UserPaint, true);
        SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.DoubleBuffer, true);
    }

    private void InitializeComponent()
    {
        tmrStars = new Timer();
        tmrStars.Enabled = true;
        tmrStars.Interval = 5000;
        tmrStars.Tick += tmrStarsTick;

        Random rndPoint = new Random();

        for (int i = 0; i < 100; i++)
            ptStars[i] = new Point(rndPoint.Next(0, 1000), rndPoint.Next(0, 1000));

        Text = "Exercise";
        ClientSize = new Size(825, 825);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void tmrStarsTick(object sewnder, EventArgs e)
    {
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        int radius = 80;
        Random rndStars = new Random();
        Random rndPoint = new Random();
        Form closedCircuit = new Form();
        Random rndStarSize = new Random();

        Point[] ptStarPolygons = new Point[100];
        Point ptCenter = new Point(ClientRectangle.Width / 2, ClientRectangle.Height / 2);
        Rectangle rectSun = new Rectangle(ptCenter.X - radius - 5, ptCenter.Y - radius - 5, (radius * 2) + 10, (radius * 2) + 10);
            Rectangle rSun = rectSun;
            rSun.Inflate(-10, -10);
        LinearGradientBrush lgbSun = new LinearGradientBrush(rSun, Color.Maroon, Color.Yellow, LinearGradientMode.ForwardDiagonal);

        e.Graphics.Clear(Color.Black);


        for (int i = 0; i < 100; i++)
            e.Graphics.FillRectangle(Brushes.White, new Rectangle(ptStars[i].X - 1, ptStars[i].Y - 1, 2, 2));

        lock(closedCircuit)
        {
            for (int i = 0; i < 100; i++)
            {
                ptStars[i] = new Point(rndPoint.Next(0, ClientRectangle.Width), rndPoint.Next(0, ClientRectangle.Height));
                Point pt1 = new Point(ptStars[i].X - rndStarSize.Next(1, 3), ptStars[i].Y);
                Point pt2 = new Point(ptStars[i].X, ptStars[i].Y - rndStarSize.Next(2, 6));
                Point pt3 = new Point(ptStars[i].X + rndStarSize.Next(1, 3), ptStars[i].Y);
                Point pt4 = new Point(ptStars[i].X, ptStars[i].Y + rndStarSize.Next(2, 6));
                Point[] ptStarPolygon = { pt1, pt2, pt3, pt4 };

                e.Graphics.FillPolygon(Brushes.White, ptStarPolygon);
            }
        }

        lock (closedCircuit)
        {

            e.Graphics.FillEllipse(lgbSun, rSun);
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 25, ptCenter.Y - radius - 25, (radius * 2) + 50, (radius * 2) + 50));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 75, ptCenter.Y - radius - 75, (radius * 2) + 150, (radius * 2) + 150));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 125, ptCenter.Y - radius - 125, (radius * 2) + 250, (radius * 2) + 250));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 175, ptCenter.Y - radius - 175, (radius * 2) + 350, (radius * 2) + 350));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 225, ptCenter.Y - radius - 225, (radius * 2) + 450, (radius * 2) + 450));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 275, ptCenter.Y - radius - 275, (radius * 2) + 550, (radius * 2) + 550));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 325, ptCenter.Y - radius - 325, (radius * 2) + 650, (radius * 2) + 650));
        }

        base.OnPaint(e);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();
        Application.Run(exo);

        return 0;
    }
}

Introduction to Atomicity

Introduction to Atomicity

Normally, you should avoid sharing a lock. If you need to use many critical sections in your code, declare a variable for each. The lock variables can be of the same type or different types, as long as their names are different. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

public class Exercise : Form
{
    Timer tmrStars;

    King heir = new King(24);
    House protection = new House();
    Form closedCircuit = new Form();
    
    Point[] ptStars = new Point[100];

    public Exercise()
    {
        InitializeComponent();

        SetStyle(ControlStyles.UserPaint, true);
        SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.DoubleBuffer, true);
    }

    private void InitializeComponent()
    {
        tmrStars = new Timer();
        tmrStars.Enabled = true;
        tmrStars.Interval = 5000;
        tmrStars.Tick += tmrStarsTick;

        Random rndPoint = new Random();

        for (int i = 0; i < 100; i++)
            ptStars[i] = new Point(rndPoint.Next(0, 1000), rndPoint.Next(0, 1000));

        Text = "Exercise";
        ClientSize = new Size(825, 825);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void tmrStarsTick(object sewnder, EventArgs e)
    {
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        int radius = 80;
        Random rndStars = new Random();
        Random rndPoint = new Random();
        Random rndStarSize = new Random();

        Point[] ptStarPolygons = new Point[100];
        Point ptCenter = new Point(ClientRectangle.Width / 2, ClientRectangle.Height / 2);
        Rectangle rectSun = new Rectangle(ptCenter.X - radius - 5, ptCenter.Y - radius - 5, (radius * 2) + 10, (radius * 2) + 10);
            Rectangle rSun = rectSun;
            rSun.Inflate(-10, -10);
        LinearGradientBrush lgbSun = new LinearGradientBrush(rSun, Color.Maroon, Color.Yellow, LinearGradientMode.ForwardDiagonal);

        e.Graphics.Clear(Color.Black);


        for (int i = 0; i < 100; i++)
            e.Graphics.FillRectangle(Brushes.White, new Rectangle(ptStars[i].X - 1, ptStars[i].Y - 1, 2, 2));

        lock(closedCircuit)
        {
            for (int i = 0; i < 100; i++)
            {
                ptStars[i] = new Point(rndPoint.Next(0, ClientRectangle.Width), rndPoint.Next(0, ClientRectangle.Height));
                Point pt1 = new Point(ptStars[i].X - rndStarSize.Next(1, 3), ptStars[i].Y);
                Point pt2 = new Point(ptStars[i].X, ptStars[i].Y - rndStarSize.Next(2, 6));
                Point pt3 = new Point(ptStars[i].X + rndStarSize.Next(1, 3), ptStars[i].Y);
                Point pt4 = new Point(ptStars[i].X, ptStars[i].Y + rndStarSize.Next(2, 6));
                Point[] ptStarPolygon = { pt1, pt2, pt3, pt4 };

                e.Graphics.FillPolygon(Brushes.White, ptStarPolygon);
            }
        }

        lock (heir)
        {

            e.Graphics.FillEllipse(lgbSun, rSun);
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 25, ptCenter.Y - radius - 25, (radius * 2) + 50, (radius * 2) + 50));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 75, ptCenter.Y - radius - 75, (radius * 2) + 150, (radius * 2) + 150));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 125, ptCenter.Y - radius - 125, (radius * 2) + 250, (radius * 2) + 250));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 175, ptCenter.Y - radius - 175, (radius * 2) + 350, (radius * 2) + 350));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 225, ptCenter.Y - radius - 225, (radius * 2) + 450, (radius * 2) + 450));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 275, ptCenter.Y - radius - 275, (radius * 2) + 550, (radius * 2) + 550));
            e.Graphics.DrawEllipse(Pens.White, new Rectangle(ptCenter.X - radius - 325, ptCenter.Y - radius - 325, (radius * 2) + 650, (radius * 2) + 650));
        }

        lock (protection)
        {
            e.Graphics.FillEllipse(Brushes.Orange, new Rectangle((ClientRectangle.Width / 2) - 100, (ClientRectangle.Height / 2) + 45, 32, 32));
            e.Graphics.FillEllipse(Brushes.DarkOrchid, new Rectangle((ClientRectangle.Width / 2) + 120, (ClientRectangle.Height / 2) - 70, 45, 45));
            e.Graphics.FillEllipse(Brushes.Blue, new Rectangle((ClientRectangle.Width / 2) + 130, (ClientRectangle.Height / 2) + 110, 50, 50));
            e.Graphics.FillEllipse(Brushes.Maroon, new Rectangle((ClientRectangle.Width / 2) - 80, (ClientRectangle.Height / 2) - 280, 75, 75));
            e.Graphics.FillEllipse(Brushes.DarkOrange, new Rectangle((ClientRectangle.Width / 2) - 300, (ClientRectangle.Height / 2) + 120, 65, 65));
            e.Graphics.FillEllipse(Brushes.Wheat, new Rectangle((ClientRectangle.Width / 2) + 220, (ClientRectangle.Height / 2) - 200, 70, 70));
            e.Graphics.FillEllipse(Brushes.DarkKhaki, new Rectangle((ClientRectangle.Width / 2) - 350, (ClientRectangle.Height / 2) - 180, 60, 60));
            e.Graphics.FillEllipse(Brushes.LawnGreen, new Rectangle((ClientRectangle.Width / 2) + 180, (ClientRectangle.Height / 2) + 335, 35, 35));
        }

        base.OnPaint(e);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();
        Application.Run(exo);

        return 0;
    }
}

class House { }

class King
{
    public King(int level)
    {
    }
}

Introduction to Atomicity

Introduction to Atomicity

In the same way, avoid using the same string as the object (name) of many locks.

Nesting a Lock

You can create a critical section inside another critical section. Each section must use its own lock. The nested critical section can appear anywhere inside the nesting section, such as before some of its code lines, after some code lines but before other code lines, or just before the closing curly bracket. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        object classRoom = new object();
        object lockerRoom = new object();
        Form frmExercise = new Form();
        
        frmExercise.Text = "Exercise";
        frmExercise.ClientSize = new System.Drawing.Size(500, 370);
        frmExercise.StartPosition = FormStartPosition.CenterScreen;

        frmExercise.Paint += (sender, e) =>
        {
            
	    lock(classRoom)
            {
                Point pt1 = new Point( 50, 100);
                Point pt2 = new Point(150,  50);
                Point pt3 = new Point(450,  50);
                Point pt4 = new Point(350, 100);
                Point pt5 = new Point(450, 250);
                Point pt6 = new Point(350, 300);

                Point[] ptsTopFace = new Point[]{ pt1, pt2, pt3, pt4 };
                Point[] ptsRightFace = new Point[]{ pt4, pt3, pt5, pt6 };

                e.Graphics.FillRectangle(Brushes.Maroon, new Rectangle(pt1.X, pt1.Y, 300, 200));
                e.Graphics.FillPolygon(Brushes.Orange, ptsTopFace);
                e.Graphics.FillPolygon(Brushes.Bisque, ptsRightFace);

                lock(lockerRoom)
                {
                    Pen pnBorder = new Pen(Color.Black, 1);
                    e.Graphics.DrawRectangle(pnBorder, new Rectangle(pt1.X, pt1.Y, 300, 200));
                    e.Graphics.DrawLine(pnBorder, pt1, pt2);
                    e.Graphics.DrawLine(pnBorder, pt2, pt3);
                    e.Graphics.DrawLine(pnBorder, pt3, pt4);
                    e.Graphics.DrawLine(pnBorder, pt3, pt5);
                    e.Graphics.DrawLine(pnBorder, pt5, pt6);
                }
            }
        };

        Application.EnableVisualStyles();
        Application.Run(frmExercise);

        return 0;
    }
}

Nesting a Lock

In the same way, you can nest many critical sections in one, or nest a critical section in one that itself is nested. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        object classRoom = new object();
        object lockerRoom = new object();
        Form frmExercise = new Form();
        
        frmExercise.Text = "Exercise";
        frmExercise.ClientSize = new System.Drawing.Size(500, 370);
        frmExercise.StartPosition = FormStartPosition.CenterScreen;

        frmExercise.Paint += (sender, e) =>
        {
            lock(classRoom)
            {
                Point pt1 = new Point( 50, 100);
                Point pt2 = new Point(150,  50);
                Point pt3 = new Point(450,  50);
                Point pt4 = new Point(350, 100);
                Point pt5 = new Point(450, 250);
                Point pt6 = new Point(350, 300);
                Rectangle face = new Rectangle(pt1.X, pt1.Y, 300, 200);

                Point[] ptsTopFace = new Point[]{ pt1, pt2, pt3, pt4 };
                Point[] ptsRightFace = new Point[]{ pt4, pt3, pt5, pt6 };

                e.Graphics.FillRectangle(Brushes.Maroon, face);
                e.Graphics.FillPolygon(Brushes.Orange, ptsTopFace);
                e.Graphics.FillPolygon(Brushes.Bisque, ptsRightFace);

                lock(lockerRoom)
                {
                    Pen pnBorder = new Pen(Color.Black, 1);
                    e.Graphics.DrawRectangle(pnBorder, new Rectangle(pt1.X, pt1.Y, 300, 200));
                    e.Graphics.DrawLine(pnBorder, pt1, pt2);
                    e.Graphics.DrawLine(pnBorder, pt2, pt3);

                    lock("chair")
                    {
                        Pen pnBackLines = new Pen(Color.FromArgb(100, Color.Silver), 1);
                        pnBackLines.DashStyle = DashStyle.Dash;

                        Point pt7 = new Point(pt2.X,  pt5.Y);
                        
                        e.Graphics.DrawLine(pnBackLines, pt2, pt7);
                        e.Graphics.DrawLine(pnBackLines, pt7, pt5);
                        e.Graphics.DrawLine(pnBackLines, new Point(face.Left, face.Bottom), pt7);
                    }

                    e.Graphics.DrawLine(pnBorder, pt3, pt4);
                    e.Graphics.DrawLine(pnBorder, pt3, pt5);
                    e.Graphics.DrawLine(pnBorder, pt5, pt6);
                }
            }
        };

        Application.EnableVisualStyles();
        Application.Run(frmExercise);

        return 0;
    }
}

Nesting a Lock

Monitoring Threads

Introduction

While the C# language provides the lock keyword to isolate a transaction that must complete without interruption, the .NET Framework supports the locking concept through a static class named Monitor.

As we will learn in later sections, the Monitor class goes beyond the limitations of the lock keyword. For example, the C#'s lock is mostly used to create a section of code for atomicity. On the other hand, the Monitor class goes behind-the-scenes to manage the lock used by the current object such as to restrict its access and/or to release it. To be able to manage the various locks in an application, Monitor is a static class with various methods that, of course, are all static. This means that you will not declare a variable for this class. Instead, you can just call the method you need (provided you know what the method does).

Entering a Critical Section

To let you start delimiting a critical section, the Monitor class is equipped with an overloaded method named Enter that has two versions. One of them uses the following syntax:

public static void Enter(object obj)

As seen for the lock keyword, the Monitor.Enter() method takes an argument that must be a reference type. Here is an example:

using System;
using System.Threading;
using System.Windows.Forms;

public class Exercise
{
    Form frmExercise = new Form();

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Monitor.Enter(new object());

        Application.Run(frmExercise);
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Exercise exo = new Exercise();

        return 0;
    }
}

The other version of the Monitor.Enter() method uses the following syntax:

public static void Enter(object obj, ref bool lockTaken)

Besides the key, this version takes a Boolean argument as reference. This argument is the value returned by the method to indicate whether the lock was actually acquired (if it returns true) or not (if it returns false).

Exiting a Critical Section

To let you indicate the end of a critical section, the Monitor class is equipped with a method named Exit. Its syntax is:

public static void Exit(object obj)

This method takes an argument as the (same) object that was passed to the Monitor.Enter() method. For this reason, you should (must) explicitly declare a variable and pass it as argument to both methods. Here is an example:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pbxCanvas;
    private System.Windows.Forms.Timer tmrControlCircles;

    private int x;
    private bool isMovingRight;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pbxCanvas = new PictureBox();
        tmrControlCircles = new System.Windows.Forms.Timer();

        // Picture Box: Canvas
        pbxCanvas = new PictureBox();
        pbxCanvas.Dock = DockStyle.Fill;
        pbxCanvas.Paint += pbxCanvasPaint;
        Controls.Add(pbxCanvas);

        // Timer: Control Circles
        tmrControlCircles = new System.Windows.Forms.Timer();
        tmrControlCircles.Interval = 10;
        tmrControlCircles.Enabled = true;
        tmrControlCircles.Tick += tmrControlCirclesTick;

        // Form: Exercise
        MaximizeBox = false;
        Load += ExerciseLoad;
        Text = "Animation - Line";
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(650, 480);
    }

    private void ExerciseLoad(object sender, EventArgs e) {
        x = 0;
        isMovingRight = false;

        BackColor = Color.Black;
    }

    private void pbxCanvasPaint(object Sender, PaintEventArgs e)
    {
        object line = new object();

        Monitor.Enter(line);

        // If the status of the origin indicates that it is moving right,
        // then increase the horizontal axis
        if (isMovingRight == true)
            x++;

        else // If it's moving left, then decrease the horizontal movement
            x--;

        /* Collision: if the axis hits the right side of the screen,
         then set the horizontal moving status to "Right", which will be used
         by the above code */
        if ((x + 40) > ClientSize.Width)
            isMovingRight = false;

        if (x < 0)
            isMovingRight = true;

        // Draw the vertical axis
        e.Graphics.DrawLine(Pens.Aqua, x + 20, 0, x + 20, ClientSize.Height);

        Monitor.Exit(line);
    }

    private void tmrControlCirclesTick(object sender, EventArgs e)
    {
        pbxCanvas.Invalidate();
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Exercise());

        return 0;
    }
}

Exiting a Critical Section

Exiting a Critical Section

After using a lock, to indicate to the other objects that the lock has been released, you should create a try...finally block in your code. In this case, call the Monitor.Exit() method in the finally section. This can be done as follows:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pbxCanvas;
    private System.Windows.Forms.Timer tmrControlCircles;

    private int x;
    private bool isMovingRight;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pbxCanvas = new PictureBox();
        tmrControlCircles = new System.Windows.Forms.Timer();

        // Picture Box: Canvas
        pbxCanvas = new PictureBox();
        pbxCanvas.Dock = DockStyle.Fill;
        pbxCanvas.Paint += pbxCanvasPaint;
        Controls.Add(pbxCanvas);

        // Timer: Control Circles
        tmrControlCircles = new System.Windows.Forms.Timer();
        tmrControlCircles.Interval = 10;
        tmrControlCircles.Enabled = true;
        tmrControlCircles.Tick += tmrControlCirclesTick;

        // Form: Exercise
        MaximizeBox = false;
        Load += ExerciseLoad;
        Text = "Animation - Line";
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(650, 480);
    }

    private void ExerciseLoad(object sender, EventArgs e) {
        x = 0;
        isMovingRight = false;

        BackColor = Color.Black;
    }

    private void pbxCanvasPaint(object Sender, PaintEventArgs e)
    {
        object line = new object();

        Monitor.Enter(line);

        try
        {
            // If the status of the origin indicates that it is moving right,
            // then increase the horizontal axis
            if (isMovingRight == true)
                x++;
            else // If it's moving left, then decrease the horizontal movement
                x--;

            /* Collision: if the axis hits the right side of the screen,
             then set the horizontal moving status to "Right", which will be used
             by the above code */
            if ((x + 40) > ClientSize.Width)
                isMovingRight = false;

            if (x < 0)
                isMovingRight = true;

            // Draw a vertical line
            e.Graphics.DrawLine(Pens.Aqua, x + 20, 0, x + 20, ClientSize.Height);
        }
        finally
        {
            Monitor.Exit(line);
        }
    }

    private void tmrControlCirclesTick(object sender, EventArgs e)
    {
        pbxCanvas.Invalidate();
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Exercise());

        return 0;
    }
}

In the same way, you can create as many monitors as you want as long as each call to Monitor.Enter() and Monitor.Exit() use the same object. Here are examples:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pbxCanvas;
    private System.Windows.Forms.Timer tmrControlCircles;

    private int x;
    private int y;
    private bool isMovingDown;
    private bool isMovingRight;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pbxCanvas = new PictureBox();
        tmrControlCircles = new System.Windows.Forms.Timer();

        // Picture Box: Canvas
        pbxCanvas = new PictureBox();
        pbxCanvas.Dock = DockStyle.Fill;
        pbxCanvas.Paint += pbxCanvasPaint;
        Controls.Add(pbxCanvas);

        // Timer: Control Circles
        tmrControlCircles = new System.Windows.Forms.Timer();
        tmrControlCircles.Interval = 10;
        tmrControlCircles.Enabled = true;
        tmrControlCircles.Tick += tmrControlCirclesTick;

        // Form: Exercise
        MaximizeBox = false;
        Load += ExerciseLoad;
        Text = "Animation - Circles";
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(650, 480);
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        x = 0;
        y = 0;
        isMovingRight = false;
        isMovingDown = false;

        BackColor = Color.Black;
    }

    private void pbxCanvasPaint(object Sender, PaintEventArgs e)
    {
        object vertical = new object();
        object horizontal = new object();

        Monitor.Enter(vertical);

        try
        {
            // If the status of the origin indicates that it is moving right,
            // then increase the horizontal axis
            if (isMovingRight == true)
                x++;
            else // If it's moving left, then decrease the horizontal movement
                x--;

            /* Collision: if the axis hits the right side of the screen,
             then set the horizontal moving status to "Right", which will be used
             by the above code */
            if ((x + 40) > ClientSize.Width)
                isMovingRight = false;

            if (x < 0)
                isMovingRight = true;

            // Draw the vertical axis
            e.Graphics.DrawLine(Pens.Aqua, x + 20, 0, x + 20, ClientSize.Height);
        }
        finally
        {
            Monitor.Exit(vertical);
        }

        Monitor.Enter(horizontal);

        try
        {
            // If the status of the origin indicates that it is moving down,
            // then increase the vertical axis
            if (isMovingDown == true)
                y++;
            else // Otherwise, decrease it
                y--;

            if ((y + 40) > ClientSize.Height)
                isMovingDown = false;

            if (y < 0)
                isMovingDown = true;

            // Draw the vertical axis
            e.Graphics.DrawLine(Pens.Aqua, 0, y + 20, ClientSize.Width, y + 20);
        }
        finally
        {
            Monitor.Exit(horizontal);
        }
    }

    private void tmrControlCirclesTick(object sender, EventArgs e)
    {
        pbxCanvas.Invalidate();
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Exercise());

        return 0;
    }
}

As we saw for locks in C#, you can nest a monitored section inside another.

Exiting a Critical Section

Exiting a Critical Section


Previous Copyright © 2014-2021, FunctionX Next