Sponsored Ad

Thursday, June 3, 2010

How to use Monitor in multithreaded application – C#

How to use Monitor in multithreaded application – C#

 

Monitor is use to maintain the critical section in multithreaded application.

Critical section is a code section where only one thread can execute the code at atime.

Monitor.Enter(this);

Code----

Monitor.Exit(this);

This statement enter the current thread into the critical section of current object “this”. Once the execution is over for current thread the another thread will get a chance to execute the same code.

Monitor.TryEnter(this);

Code----

Monitor.Exit(this);

In The above block of code TryEnter will work same as Enter but it returns the boolien values. For the first thread it will return true and enter critical section. For the second thread it will return false and enter in critical section.

Monitor.TryEnter(this,500);

Specifying time with Monitor.TryEnter function means it will block thread for 500 miliseconds.

 

How to use Monitor in multithreaded application – C# Example:

using System;
using System.Text;
using System.Threading;

namespace Console_App
{

    public class Class1
    {
        public void fun1()
        {
            Monitor.TryEnter(this,500);

            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine(" #" + i + " " + Thread.CurrentThread.GetHashCode());

            }
            Monitor.Exit(this);

        }    
    }
    public class Class2
    {
        public static void Main()
        {
            Class1 a = new Class1();
            Thread thread1 = new Thread(new ThreadStart(a.fun1));
            Thread thread2 = new Thread(new ThreadStart(a.fun1));

            thread2.Start();
            thread1.Start();

            Console.ReadLine();
        }
    }

}

1 comments:

  1. Online computer support technicians are masters of their profession who ensure your success by protecting your computers with preventative and proactive maintenance. In addition, these services are highly affordable and assist you to get the best performance out of your computers.
    ReplyDelete

Sponsored Ad

More Related Articles

Website Update

Followers