Use Monitor to control more than one Threads : Monitor « Thread « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Thread » Monitor 
20.19.6.Use Monitor to control more than one Threads
using System;
using System.Threading;

class MyClass
{
  private int counter;

  public void DoSomeWork()
  {
    lock(this)
    {
      counter++;
      // Do the work.
      for(int i = 0; i < 5; i++)
      {
        Console.WriteLine("counter: {0}, i: {1}, current thread: {2}",
          counter, i, Thread.CurrentThread.Name);
        Thread.Sleep(1000);
      }
    }
  }
}

public class MainClass
{
  public static int Main(string[] args)
  {
    MyClass w = new MyClass();

    Thread workerThreadA = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadA.Name = "A";
    Thread workerThreadB = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadB.Name = "B";
    Thread workerThreadC = new Thread(new ThreadStart(w.DoSomeWork));
    workerThreadC.Name = "C";

    // Now start each one.
    workerThreadA.Start();
    workerThreadB.Start();
    workerThreadC.Start();
    
    return 0;
  }
}
counter: 1, i: 0, current thread: A
counter: 1, i: 1, current thread: A
counter: 1, i: 2, current thread: A
counter: 1, i: 3, current thread: A
counter: 1, i: 4, current thread: A
counter: 2, i: 0, current thread: B
counter: 2, i: 1, current thread: B
counter: 2, i: 2, current thread: B
counter: 2, i: 3, current thread: B
counter: 2, i: 4, current thread: B
counter: 3, i: 0, current thread: C
counter: 3, i: 1, current thread: C
counter: 3, i: 2, current thread: C
counter: 3, i: 3, current thread: C
counter: 3, i: 4, current thread: C
20.19.Monitor
20.19.1.Use Wait() and Pulse() to create a ticking clock
20.19.2.Use Monitors
20.19.3.Monitor: Enter and Exit
20.19.4.Monitor: try to enter
20.19.5.Coordinate two threads using Monitor
20.19.6.Use Monitor to control more than one Threads
20.19.7.Increment Monitor
20.19.8.Monitor Pool
20.19.9.Throw exception between Monitor.Enter and Montor.Exit
20.19.10.Using A Monitor
20.19.11.Use lock and Monitor to coordinate Producer and Consumer
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.