Monitor: Enter : Monitor « Thread « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# / C Sharp » Thread » Monitor 




Monitor: Enter
 
using System;
using System.Threading;


public class EnterExit {
    private int result = 0;

    public void NonCriticalSection() {
        Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());

        for (int i = 1; i <= 5; i++) {
            Console.WriteLine("Result = " + result++ + "  ThreadID "
                              + Thread.CurrentThread.GetHashCode());
            Thread.Sleep(1000);
        }

        Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());
    }
    public void CriticalSection() {
        Monitor.Enter(this);
        Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());

        for (int i = 1; i <= 5; i++) {
            Console.WriteLine("Result = " + result++ + "  ThreadID " +
                              Thread.CurrentThread.GetHashCode());
            Thread.Sleep(1000);
        }
        Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());

        Monitor.Exit(this);
    }

    public static void Main(String[] args) {
        EnterExit e = new EnterExit();

        Thread nt1 = new Thread(new ThreadStart(e.NonCriticalSection));
        nt1.Start();

        Thread nt2 = new Thread(new ThreadStart(e.NonCriticalSection));
        nt2.Start();

        Thread ct1 = new Thread(new ThreadStart(e.CriticalSection));
        ct1.Start();

        Thread ct2 = new Thread(new ThreadStart(e.CriticalSection));
        ct2.Start();
    }
}

 














Related examples in the same category
1.Monitor.TryEnter
2.Monitor.Pulse
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.