< Thread Pools, Synchronization & Critical Sections | Main | Asynchronous & C++ I/O Program Example >

 


 

Chapter 3 Part 6:

Threading and the Asynchronous Pattern

 

 

What do we have in this chapter 3 Part 6?

  1. C# Critical Section Program Example

  2. VB .NET Critical Section Program Example

 

 

C# Critical Section Program Example

 

Create a new console application. You can use the name shown in the following Figure if you want.

 

C# Critical Section Program Example - new console mode project creation

 

Add/edit the following codes.

 

using System;

using System.Threading;

 

// <summary>

// This example demonstrates how to use the Monitor class to protect access to

// a shared object when multiple threads read and write data to the shared object.

// </summary>

namespace CriticalSectionCS

{

    class Program

    {

        // <summary>

        // The main entry point for the application.

        // </summary>

        static byte[ ] m_Buffer = new byte[32];

 

        [STAThread]

        static void Main(string[ ] args)

        {

            ThreadStart ThreadMethod1 = new ThreadStart(MyBufferWriter1);

            ThreadStart ThreadMethod2 = new ThreadStart(MyBufferWriter2);

            Thread MyThread1 = new Thread(ThreadMethod1);

            Thread MyThread2 = new Thread(ThreadMethod2);

            Console.WriteLine("Instantiating ThreadStart & Thread objects...");

 

            try

            {

                Console.WriteLine("In Main()...");

                MyThread1.Start();

                Console.WriteLine("Start() for MyThread1 is OK...");

            }

            catch (Exception e)

            {

                Console.WriteLine("The thread failed to start with error: " + e.Message);

            }

 

            try

            {

                MyThread2.Start();

                Console.WriteLine("Start() for MyThread2 is OK...");

            }

            catch (Exception e)

            {

                Console.WriteLine("The thread failed to start with error: " + e.Message);

            }

 

            Console.WriteLine("Looping - writing for both buffers, Enter(), Write(), Exit() & Sleep(200)...");

            for (int i = 0; i < 10; i++)

            {

                Console.WriteLine("Pass #" + i.ToString());

                Monitor.Enter(m_Buffer);

 

                for (int j = 0; j < m_Buffer.Length; j++)

                {

                    Console.Write(m_Buffer[j].ToString());

                }

                Console.WriteLine();

                Monitor.Exit(m_Buffer);

                Thread.Sleep(200);

            }

            Console.WriteLine("Aborting both threads...");

            MyThread1.Abort();

            MyThread2.Abort();

        }

 

        public static void MyBufferWriter1()

        {

            Console.WriteLine("In MyBufferWriter1()...Enter(), assign 1, Exit() & Sleep(300)...");

            try

            {

                for (int j = 0; j < 420; j++)

                {

                    Monitor.Enter(m_Buffer);

 

                    for (int i = 0; i < m_Buffer.Length; i++)

                    {

                        m_Buffer[i] = 1;

                    }

 

                    Monitor.Exit(m_Buffer);

                    Thread.Sleep(300);

                }

            }

            catch (ThreadAbortException e)

            {

                Console.WriteLine("MyBufferWriter1 caught abort exception: " + e.Message);

            }

        }

 

        public static void MyBufferWriter2()

        {

            Console.WriteLine("In MyBufferWriter2()...Enter(), assign 2, Exit() & Sleep(400)...");

            try

            {

                for (int j = 0; j < 420; j++)

                {

                    Monitor.Enter(m_Buffer);

 

                    for (int i = 0; i < m_Buffer.Length; i++)

                    {

                        m_Buffer[i] = 2;

                    }

 

                    Monitor.Exit(m_Buffer);

                    Thread.Sleep(400);

                }

            }

            catch (ThreadAbortException e)

            {

                Console.WriteLine("MyBufferWriter2 caught abort exception: " + e.Message);

            }

        }

    }

}

 

Build and run the project. The following is a sample output.

 

C# Critical Section Program Example - an output sample

 

Well, running the same program second times may produce slightly different output.

 

VB .NET Critical Section Program Example

 

Create a new class library project. Use the following name for the project and solution if you want it.

 

VB .NET Critical Section Program Example - a class library new project creation  

 

Add the following codes.

 

Imports System

Imports System.Threading

 

' This example demonstrates how to use the Monitor class to protect access to

' a shared object when multiple threads read and write data to the shared object.

Public Class Class1

    ' The main entry point for the application.

    Shared m_Buffer(32) As Byte

 

    Shared Sub Main()

 

        Console.WriteLine("Instantiating ThreadStart & Thread objects...")

        Dim ThreadMethod1 As ThreadStart = New ThreadStart(AddressOf MyBufferWriter1)

        Dim ThreadMethod2 As ThreadStart = New ThreadStart(AddressOf MyBufferWriter2)

        Dim MyThread1 As Thread = New Thread(ThreadMethod1)

        Dim MyThread2 As Thread = New Thread(ThreadMethod2)

 

        Try

            MyThread1.Start()

            Console.WriteLine("Starting MyThread1 using Start() is OK...")

        Catch e As Exception

            Console.WriteLine("The thread failed to start with error: " + e.Message)

        End Try

        Try

            MyThread2.Start()

            Console.WriteLine("Starting MyThread2 using Start() is OK...")

        Catch e As Exception

            Console.WriteLine("The thread failed to start with error: " + e.Message)

        End Try

 

        Dim i As Integer

        Console.WriteLine("Enter(), Write(), Exit() & Sleep(200)...")

        For i = 0 To 9

            Console.WriteLine("Pass #" + i.ToString())

            Monitor.Enter(m_Buffer)

 

            Dim j As Integer

            For j = 0 To m_Buffer.GetUpperBound(0) - 1

                Console.Write(m_Buffer(j).ToString())

            Next

            Console.WriteLine()

            Monitor.Exit(m_Buffer)

            Thread.Sleep(200)

        Next

        Console.WriteLine("Aborting both threads...")

        MyThread1.Abort()

        MyThread2.Abort()

    End Sub

 

    Shared Sub MyBufferWriter1()

        Try

            Dim j As Integer

            Console.WriteLine("In MyBufferWriter1 sub - Enter(), assign 1, Exit & Sleep(300)...")

            For j = 1 To 420

                Monitor.Enter(m_Buffer)

 

                Dim i As Integer

                For i = 0 To m_Buffer.GetUpperBound(0) - 1

                    m_Buffer(i) = 1

                Next

                Monitor.Exit(m_Buffer)

                Thread.Sleep(300)

            Next

 

        Catch e As ThreadAbortException

            Console.WriteLine("MyBufferWriter1 caught abort exception: " + e.Message)

        End Try

    End Sub

 

    Shared Sub MyBufferWriter2()

        Try

            Console.WriteLine("In MyBufferWriter2 sub - Enter(), assign 2, Exit & Sleep(400)...")

            Dim j As Integer

            For j = 1 To 420

                Monitor.Enter(m_Buffer)

                Dim i As Integer

                For i = 0 To m_Buffer.GetUpperBound(0) - 1

                    m_Buffer(i) = 2

                Next

                Monitor.Exit(m_Buffer)

                Thread.Sleep(400)

            Next

 

        Catch e As ThreadAbortException

            Console.WriteLine("MyBufferWriter2 caught abort exception: " + e.Message)

        End Try

    End Sub

End Class

 

Build and run the project. You may need to change the Output type: to Console Application and Startup object: to Sub Main, to run this project.

 

VB .NET Critical Section Program Example - invoking the Project's Properties page

 

VB .NET Critical Section Program Example - changing the application type from DLL to EXE and set the startup object to Main() subroutine

 

The following snapshot is the sample output.

 

VB .NET Critical Section Program Example - sample output in action

 

 

 


 

< Thread Pools, Synchronization & Critical Sections | Main | Asynchronous & C++ I/O Program Example >