Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Thread Synchronization using VS.NET 2005

Thread Synchronization using VS.NET 2005

When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.

Author Rank:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 312
Total page views :  32426
Rating :
 4/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SynchronizedThreads.zip
 
ArticleAd
Become a Sponsor



Synchronization is achieved in C# through the use of Monitors. Monitor is a class present in System.Threading namespace. This class provides the synchronization of threading objects using locks and wait/signals.

Monitor has the following features:

 

  • Is associated with an object on demand.
  • Is unbound, i.e., can be called directly from any Context
  • Can not be instantiated.

Monitor exposes their ability to take and release the sync block lock on an object on demand via Enter, TryEnter and Exit.

 

The Wait, Pulse and PulseAll methods are related to SyncBlocks. It is necessary to be in a synchronized region on an object before calling Wait or Pulse on that object. Wait releases the lo9ck if it is held and waits to be notified. When Wait is notified, it returns and has obtained the lock again. Pulse signals for next thread in wait queue to proceed.

 

Monitor.Enter Method

 

The Monitor.Enter method obtains the monitor lock for an object. This method will block if another thread holds the lock. It will not block if the current thread holds the lock, however the caller must ensure that the same number of Exit calls are made as there were Enter Calls.

 

Enter the Monitor for an object. An object is passed as a parameter. This call will block if another thread has entered the Monitor of the same object. It will not block if the current thread has previously entered the Monitor, however the caller must ensure that the same number of Exit calls are made as there were Enter calls.

 

The general syntax for the Enter method is given as follows:

 

public static void Enter (object obj);

 

Where

 

obj represents an object on which to acquire the monitor lock.

 

The Thread.Interrupt method can interrupt threads waiting to enter a Monitor on an object. ThreadInterruptedException will be thrown if the thread was interrupted during a waiting state.

 

If another thread has executed an Enter on the object but not yet the corresponding Exit the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more then once (and it will not block); however, an equal number of Exit calls must be invoked before other threads waiting of the object will unblock.

 

Monitor.TryEnter Method

 

Similar to Enter, but will never block, or will only block for a certain amount of time.

 

Monitor.Exit Method

 

Releases the monitor lock. If one or more threads are waiting to acquire the lock, and the current thread has executed Exit, AS many times as it has executed Enter, one of the Treads will be unblocked and allowed to proceed.

 

The general syntax is given as follows:

 

public static void Exit(object obj);

 

Where

 

obj represents an object on which to release the monitor lock.

 

If the current thread owns the lock, the lock count is decremented for the specified object. If the count goes to zero (Exit has been executed as many times as Enter), other threads waiting on the object can acquire the lock.

 

Monitor.Wait Method

 

Waits for notifications passed by the Common Language Runtime from the object (via the Pulse or PluseAll method). The Wait method must be invoked from within a synchronized block of code

 

This method acquires the monitor withhandle for the object. If this thread holds the monitor lock for the object, it releases it. On exiting from the method, if obtains the monitor lock back.

 

Monitor.Pulse Method

 

Notifies a thread in the waiting queue of a change in the object's state. The general syntax for the method is given below

 

public static void Pulse (object obj);

 

Where

 

obj represents the object to send the pulse.

 

Monitor.PulseAll Method

 

This method sends a notification to all waiting objects. The syntax for the above method is given below:

 

public static void PulseAll(object obj);

 

Where

 

obj represents the object to send the pulse

 

The thread that currently holds the lock on this object invokes this method in order to Pulse all of the threads I the waiting queue of a change in the object's state. Shortly after the call to PulseAll, the threads in the waiting queue are moved to the ready queue , the thread that invoked PulseAll releases the lock, and the next thread(if there is one) in the ready queue is allowed to take control of the lock.

 

Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. The Pulse, PulseAll, and  Wait methods must be invoked from within a synchronized block of code.

 

This sample shows two threads writing to the console, without overwriting each other.

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

 

namespace SynchronizedThreads

{

    public class Alpha

    {

        // The method that will be called when the thread is started

        public void Beta()

        {

            int iThreadID = Thread.CurrentThread.GetHashCode();

            int cLoop = 10;

            while ((cLoop--) > 0)

            {

                //Obtain the lock

                Monitor.Enter(this); 

                Console.Write("{0} Thread, Thread.CurrentThread.Name);

                Console.WriteLine("Hash: {0}, Hello!", iThreadID);

                Thread.Sleep(500); 

                //Release the lock

                Monitor.Exit(this);

            }

        }

    }

    public class Program

    {

        public static void Main(string[] args)

        {

            Console.WriteLine("Thread Sync One Sample");

            Alpha oAlpha = new Alpha();

            //Create the 1st thread object, passing in teh Alpha.Beta
            //method via a ThreadStart delegate

            Thread oThread1 = new Thread(new ThreadStart(oAlpha.Beta));

            oThread1.Name = "Yellow"; 

            //Start the 1st thread

            oThread1.Start(); 

            // Spin waiting for teh started thread to become alive

            while (!oThread1.IsAlive) ; 

            //Create teh 2nd thread object, passing in the Alpha.Beta 

            //method via a ThreadStart delegate,

            //on teh same oAlpha instance

 

            Thread oThread2 = new Thread(new ThreadStart(oAlpha.Beta));

            oThread2.Name = "Green";

            

            // Start the 2nd Thread

            oThread2.Start();

 

            //Spin waiting ofr the started thread to start

            while (oThread2.ThreadState == ThreadState.Unstarted)

           

            return ;

           Console.ReadLine();           

        }

    }

  

}

 

The output for the above program will be as below:

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Sonu Chauhan
Sonu holds B. Sc. (Mathmatics, Physics & Statistics) and MCA (Master's of Computer Applications) degrees. Currently he is working with Merrill Lynch. India and has extensive experience in web technologies using .NET and SQL Reporting services. Sonu also has good hands on experience in Micorosoft Content Management Server.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SynchronizedThreads.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved