ManualResetEvent in C#

Introduction

ManualResetEvent is One of the Most important topic in C# threading. 
This helps to manage Synchronize Threading with the help of Signals.

Those who wanted to learn advanced Threading, this topic is for them.
You can check AutoResetEvent for more information.

Description

ManualResetEvent  basically consists of 2 parts.

  • WaitOne()
  • Set()
WaitOne() - Allow the thread in a halt mode 
Set() - Give signal to thread to continue from where the thread stopped.

Program Skeleton


        static ManualResetEvent manualreset = new ManualResetEvent(false);

        public static void Main()
        {
            Thread thread1 = new Thread(new ThreadStart(ManualResetMethod));
            thread1.Start();            
            manualreset.Set();    
        }

         public static void ManualResetMethod()
        {
            //Write Here
            manualreset.WaitOne();
            //Write Here                   
        }




Flow Chart Diagram

Manual-Reset-Event-C#
Manual-Reset-Event


Lets understand the above diagram.

  • As per the above diagram we need to create a thread 
  • Start a thread.
  • Call WaitOne() several times with in the method which will make the execution Pause.
  • Call the Set() which will send signal to all WaitOne() to resume the execution.
  • This leads to give the complete output .

Lets Understand the above diagram with a simple program.

Program

class ManualResetEventExample
    {
        static ManualResetEvent manualreset = new ManualResetEvent(false);
        public static void Main()
        {
            Thread thread1 = new Thread(new ThreadStart(ManualResetMethod));
            thread1.Start();
            Console.ReadKey();
            manualreset.Set();//For manual reset only 1 "Set" required for all "WaitOne"
            Console.ReadKey();
            
        }
        public static void ManualResetMethod()
        {
            manualreset.WaitOne();
            Console.WriteLine("Thread started.....");
            manualreset.WaitOne();
            Console.WriteLine("Thread Ended.....");
            manualreset.WaitOne();
            Console.WriteLine("Thread2 Started.....");
            manualreset.WaitOne();
            Console.WriteLine("Thread2 Ended.....");
        }
    }


Thread Output

Manual-Reset-Event-Output
Manual-Reset-Event-Output












Conclusion


  • ManualResetEvent will help to Pause and Resume the thread.
  • WaitOne() helps to pause the thread.
  • Set() used to Resume thread.
  • For each All WaitOne() one Set() is required to resume the thread unlike AutoResetEvent.






Share:

AutoResetEvent in C#

Introduction

Lets Understand One of the important part of Threading . 
Auto-Reset-Event class is one of the most important part of the Threading which helps to Manage Synchronize threading with the help of Signals.

Also we will discuss WaitOne() and Set() which will use in AutoResetEvent.

AutoResetEvent just like ManualResetEvent with a small difference which we will discuss here.

This use System.Threading namespace.

AutoResetEvent Flow


AutoResetEvent,autoresetevent,threads,auto reset event,.net,manual reset event,manualresetevent,multithreading,semaphore,threading,c# tutorial,how to create auto reset event in c#,mutex,async,step by step c#,how to createevent in c++,how to create event in c#,thread,step by step .net,computer,how to create manual reset event in c,learn .net,education
AutoResetEvent


Description


  • Create a thread as below.

            Thread thread1 = new Thread(autoresetevent);
            thread1.Start();

  • Create a function called autoresetevent which has below code.
 public static void autoresetevent()
        {
            Console.WriteLine("Thread Started--1.....");
            autoevent.WaitOne();  //Used to stop executing thread
            Console.WriteLine("Thread ended--1.....");            
            Console.WriteLine("Thread Started--2.....");
            autoevent.WaitOne();//Used to stop executing thread
            Console.WriteLine("Thread ended--2.....");
        }


  • Autoresetevent has two methods 
        a. WaitOne();
       b. Set()       
WaitOne() used to keep the thread in a halt mode.
Set() used to give the signal to continue execution which is in halt mode.

Lets Understand with a complete program.

class AutoResetEvent_Example
    {
        static AutoResetEvent autoevent = new AutoResetEvent(false);
        public static void Main()
        {
            Thread thread1 = new Thread(autoresetevent);
            thread1.Start();
            Console.ReadKey();
            autoevent.Set();
            Console.ReadKey();
            autoevent.Set();//For auto reset same number of "Set"                                                  //required for each "WaitOne"
           Console.ReadKey();

        }
        public static void autoresetevent()
        {
            Console.WriteLine("Thread Started--1.....");
            autoevent.WaitOne();
            Console.WriteLine("Thread ended--1.....");            
            Console.WriteLine("Thread Started--2.....");
            autoevent.WaitOne();
            Console.WriteLine("Thread ended--2.....");
        }
    }

In the above example we can check the below statement 
        static AutoResetEvent autoevent = new AutoResetEvent(false);

Constructor of the AutoResetEvent class can be True or False.

True-When the initial state is signaled 
FalseWhen the initial state is not signaled 

Program OutPut



In the above output, thread stop executing after the 1st statement.
Once you press ENTER then next 2 statement will be executed and after that last statement gets executed.

When the constructor value of the AutoResetEvent class is True then 3 statement will execute when we run the application , after that last statement will be executed.

Conclusion

  1. AutoResetEvent  does not allow the thread to execute complete statement at a time.
  2. WaitOne() used to keep the thread in a halt mode.
  3. Set() used to give the signal to continue execution which is in halt mode.
  4. For Each WaitOne() , Set()  is required to continue the thread.

Share:

Serial port communication with Multiple Application

Can two Application Communicate with a single Port?

When two applications communicates with a serial port i.e. When One application send data to another application using a serial port then you will get an error . So this means you can not use a serial port in two application.

What is the Solution of it?

Lets discuss and find the solution of it.

Solution
  • Create an window application whose design as below and add the Baud Rate,Data Bit,Stop Bit,Parity Bit value.

Serial Port Form Design



  • Then browse virtual serial port driver(VSPD) and install it.
  • Open the driver which looks like below.
  • Go to "Manage Ports"  tab, select two ports and click "Add Pair" as below Image.













  • After Pairing you can see the highlighted part in the image.






  • Added the code for the respective button in the Form control code view.
 public partial class SerialPortDataReceived_New : Form
    {
        string[] port = SerialPort.GetPortNames();


        SerialPort serialport;
        public SerialPortDataReceived_New()
        }
        void Serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        private void btnConnect_Click(object sender, EventArgs e)



        {

            InitializeComponent();
            methodserial();

        public void methodserial()

        {
            foreach (var item in port)
                cbPort.Items.Add(item);
            btnConnect.Enabled = true;
            btnDisconnect.Enabled = false;
        }

        {                    

            string indata = serialport.ReadExisting();
            txtSent.Text = "Received Data " + indata;
         }

        {

            try
            {
                string PortName = cbPort.Text;
                int BaudRate = Convert.ToInt32(cbBaudRate.Text);
                Parity parity = (Parity)Enum.Parse(typeof(Parity), cbParityBit.Text);
                StopBits stopbit = (StopBits)Enum.Parse(typeof(StopBits), cbStopBit.Text);
                int databit = Convert.ToInt32(cbDataBit.Text);
                ConnectSerialPort(PortName, BaudRate, parity, stopbit, databit);
                serialport.DataReceived += new SerialDataReceivedEventHandler(Serialport_DataReceived);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
         }
        public void ConnectSerialPort(string portname, int BaudRate, Parity parity, StopBits stopbit, int databit)
        {
            serialport = new SerialPort(portname, BaudRate, parity, databit, stopbit);
            if(!serialport.IsOpen)
            serialport.Open();
            btnConnect.Enabled = false;
            btnDisconnect.Enabled = true;
        }
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            btnDisconnect.Enabled = false;
            btnConnect.Enabled = true;
            if(serialport.IsOpen)
            serialport.Close();
        }
        string str;
        private void btnSend_Click(object sender, EventArgs e)
        {
            
            str += TextBox1.Text;            
            serialport.Write(str);
            txtSent.Text = str;
            
        }
    }
Setup Completed...............................

Lets us go to the application Bin/Debug folder and run two instance of the application.





























You can see whatever i am sending from second application is received by 1st application.


Conclusion

  • Two application can not use single port.

  • In serial port one application lock the port , so that other application can not use the same port.

  • To enable two application to communicate with each other we need to create two virtual port and do the Pairing to it.

  • One application can send and the other application can receive data by using Pairing.

Share:

ReadOnlyCollection in CSharp

Introduction





ReadOnlyCollection<T> is a collection which wrap List<T> and do not allow any modification in it.

Any modification in List<T> will be reflected to the ReadOnlyCollection<T>.

We can present ReadOnlyCollection as below 


ReadOnlyCollection<T> readonlyvar=new ReadOnlyCollection<T>(<Collection Object>);


Description

To Understand ReadOnlyCollection we need to take an example. 


  • Take a list of Student Roll number.

            List<int> list = new List<int>();
            list.Add(1);
            list.Add(3);
            list.Add(5);


  • Take ReadOnlyCollection which wrap List object.


           ReadOnlyCollection<int> readonlyvar=new                                 ReadOnlyCollection<int>(list);

  • Try to print element from ReadOnlyCollection .

          foreach(int i in readonlyvar)
           {
                Console.WriteLine(i + " ");
           }

  • After that Insert a value in the middle of the list.

         list.Insert(1, 6);

  • Again try to print the ReadOnlyCollection.

        foreach (int i in readonlyvar)
         {
                
                Console.WriteLine(i + " " );
         }


Below is the complete program which explain ReadOnlyCollection.

        public static void Main()
        {
            //Can change to the list
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(3);
            list.Add(5);
            //can not change to the collection
            ReadOnlyCollection<int> readonlyvar=new                                    ReadOnlyCollection<int>(list);
            foreach(int i in readonlyvar)
            {
                Console.WriteLine(i + " ");
            }
            Console.WriteLine("------------------------------------");
            //Any changes to the list will reflect to ReadOnlyColection              //as below
            list.Insert(1, 6);
            
            foreach (int i in readonlyvar)
            {
                
                Console.WriteLine(i + " " );
            }
            Console.ReadKey();
        }

Out-Put














Why We Need ReadOnlyCollection

  1. Readonlycollection stop allowing to modify the collection.
  2. It improve the performance of the application.
Share:

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts