Thread Synchronization in C#

Thread synchronization

Thread synchronization is a technique used in threading, Which allows only one thread to access the resources for a specific time period.No other thread interrupt till current task is completed.



Thread Synchronization
Thread Synchronization

It uses 3 techniques.
  • Monitor Or Lock
  • Mutex
  • Semaphore

1.Monitor Or Lock- It uses when multi-threaded application with single process.It uses Monitor class Or Lock keyword to synchronize the multi-threaded application.

It uses "System.Threading" Namespace.
We can demonstrate the lock keyword as below. 
lock(object)
{
}

Lets understand with an example.


lock Example

class ThreadLock
    {
        public static void Main()
        {            
            ThreadLock tl = new ThreadLock();
            Thread th = new Thread(tl.ThreadRun);
            Thread th1 = new Thread(tl.ThreadRun);
            Thread th2 = new Thread(tl.ThreadRun);
            th.Start();
            th1.Start();
            th2.Start();
            Console.WriteLine("Completed Successfully.........");
            Console.Read();
        }
        Random r = new Random();
        public int num1;
        public int num2;
        public void ThreadRun()
        {
            for (long var1 = 0; var1 < 10000000; var1++)
            {
                lock (this)
                {
                    num1 = r.Next(1, 2);
                    num2 = r.Next(1, 3);
                    int result = num1 / num2;
                    num1 = 0;
                    num2 = 0;
                }
            }
        }
    }



OUTPUT
Monitor Output
Monitor-Output






Lets Understand the above program

In Main() we created 3 threads and all the threads pointing to the same method ThreadRun().

In ThreadRun() we have a long running loop and trying to divide 2 numbers. With in the for Loop we used lock synchronization technique to synchronize the program. That means only one thread can use the resources at a time and program can run smoothly.

2. Mutex-  It uses when we use multi-threaded application with single or multiple processes. It is similar to lock/Monitor. It uses Mutex class for multi-threaded application synchronization.

It use System.Threading Namespace.

It Uses 2 methods.

  • WaitOne() - It allows single thread to use the resources.
  • ReleaseMutex()- It release current thread and allow other thread to use the resource.

Skeleton of Mutex

Mutex mu=new Mutex();
mu.WaitOne();
mu.ReleaseMutex()

Lets Understand Mutex with a C# Program


class ThreadMutex
    {
        public static Mutex mut = new Mutex();
        public static int iteration =3;
        public static void Main()
        {            
            
                Thread thread1 = new Thread(Mutex_Method);
                Thread thread2 = new Thread(Mutex_Method);
                Thread thread3 = new Thread(Mutex_Method);
                thread1.Name = "Thread1";
                thread2.Name = "Thread2";
                thread3.Name = "Thread3";
                thread1.Start();
                thread2.Start();
                thread3.Start();
                Console.Read();
            
        }

        private static void Mutex_Method()
        {
            Console.WriteLine(Thread.CurrentThread.Name + " Started...");
            mut.WaitOne();
            Console.WriteLine("Currently " + Thread.CurrentThread.Name + " Entered...");
            Thread.Sleep(500);
            Console.WriteLine(Thread.CurrentThread.Name + " Done processing...");
            mut.ReleaseMutex();
            Console.WriteLine(Thread.CurrentThread.Name + " is released...");
        }
    }


Output
Monitor Output
Mutex-Output















In Main() we created 3 threads and all the threads pointing to the same method Mutex_Method().

In Mutex_Method() we use WaitOne() which signal the program to allow only one thread to use the resources.Other threads need to wait until the current thread finish it's work.

We use ReleaseMutex() which signal the program to release the current thread and allow other thread to use the resources.


3. Semaphore It is used for multi-threaded application . Unlike Monitor and Mutex it allows multiple thread based upon the value defined.

We can define Semaphore as below.

Semaphore semapr = new Semaphore(2,2);
 Where value passed in the above constructor is (2,2) 1st 2 is the Initial count and other 2 is the maximum count

It use System.Threading Namespace.

It Uses 2 methods.

  • WaitOne() - It allows defined number of threads to use the resources.
  • Release()- It release current threads and allow other thread to use the resources.


Note-Semaphore allows multiple threads(based upon the value defined in Semaphore constructor) to use the resources at a time.

Skeleton of Semaphore


Semaphore semap=new Semaphore (2,2);  //This allows 2 threads to use the resource at a time
semap.WaitOne();

semap.Release()

Lets Understand Semaphore with a C# Program


   class Semaphore_Example
    {
        public static Semaphore semapr = new Semaphore(2,2);
        public static void Main()
        {
            Thread thread1 = new Thread(Semaphore_Method);
            Thread thread2 = new Thread(Semaphore_Method);
            Thread thread3 = new Thread(Semaphore_Method);
            thread1.Name = "Thread1";
            thread2.Name = "Thread2";
            thread3.Name = "Thread3";
            thread1.Start();
            thread2.Start();
            thread3.Start();
            Console.Read();
        }

        private static void Semaphore_Method()

        {
            Console.WriteLine(Thread.CurrentThread.Name + " Started");
            semapr.WaitOne();
            
            Console.WriteLine(Thread.CurrentThread.Name + " Entered");
            Thread.Sleep(1000);
            Console.WriteLine(Thread.CurrentThread.Name + " Releasing.....");
            
            semapr.Release();
            
        }
    }



Output
Semaphore Output
Semaphore Output


















In Main() we created 3 threads and all the threads pointing to the same method Semaphore_Method().

In Semaphore_Method() we have implemented WaitOne() which signal the program to allow defined number of thread to use the resources.Other threads need to wait until the current thread release the resources.

We use Release() which signal the program to release the current threads and allow other threads for resources.

Things To Remember...

  • Lock/Monitor used to allow one thread at a time for a single process
  • Mutex is like Lock/Monitor but it allows multiple process.
  • Semaphore allows multiple threads to use the resources at a time.
  • Lock/Monitor has batter performance among all.



Thanks.................................



Share:

Multi-Threading Example in c#

Understand Multi threading



Before dive into the Thread Programming, we should know what is Thread and why should we use thread.

What is thread and Why we need Thread


Thread is a concept of C# which used to run code segment simultaneously by using multiple threads. 

Kernel schedule the threads asynchronously, which makes the application execution faster and no need to wait for a code segment to execute completely.
Thread is most important when the code segment like methods are taking time and need to wait for the method to execute the application.

Switching CPU between multiple threads to execute code segments is called Context Switching.

Description

Thread is nothing but a lightweight process.
We know each application runs using a process . That process use at least one thread.
So ultimately we can say each application use at least one thread by default. That is called Main thread
We can create child thread and assign the code segment to it.
Thread use CPU Usage efficiently.

Thread use System.Threading Namespace to use the Thread class methods and Properties.

Thread Life cycle

It goes through 4 steps as shown below.

  • New-When Only the Instance of the thread got created.
  • Running-When thread is in running state , that time Start() called.
  • Blocked or Hold state- When Thread got started but that time thread is in Hold state.
  • Complete or dead State- When thread ended and not run again.



Thread-Life-Cycle-C#
Multi-Threading Life Cycle In C#


Sample Multi-threading Program 

class Program
    {
        static void Main(string[] args)
        {
            Thread mythread1 = new Thread(method1);
            Thread mythread2 = new Thread(method2);
            mythread1.Start();
            mythread2.Start();
            Console.ReadKey();
        }

        private static void method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method1 " + i);
            }

        }
        private static void method2()
        {
            for (int j = 11; j <=20; j++)
            {
                Console.WriteLine( "Method2 " + j);
            }
        }        
    }

1.In the above multi-threading example we created 2 threads.
We assign the related methods to the constructor of the thread class(Highlighted).

         Thread mythread1 = new Thread(method1);            Thread mythread2 = new Thread(method2);           

2.In the next step we define 2 methods which uses loop to display numbers as shown below.

private static void method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method1 " + i);
            }

        }
        private static void method2()
        {
            for (int j = 11; j <=20; j++)
            {
                Console.WriteLine( "Method2 " + j);
            }
        }        


3.In the next step we start the thread using Start() method as shown below .
 mythread1.Start(); mythread2.Start();

After the code we need to Run the application by using Run Icon available in Visual Studio or we can press Ctrl+f5.

We can see the the below Output.
Output
Multi-threading-Output
Multi-threading Output
















In The above image you can see the values are not printed in systematic order why?

The reason behind this is CPU is shared between two threads asynchronously. That is the  reason why both method1() and method2() run asynchronously.

Benefits of Multi-Threading Application

  1. Faster Execution.
  2. Proper utilization of CPU because of Context Switching.


Demerits of Multi-Threading Application

  1. If code segment is not taking much time , then implementing threading makes an adverse affect on the application execution time.
  2. Application may fail to show expected data if  we not implement threading in a proper way.
  3. Multi-Thread makes application more Complex , this means difficult to debug and mentain multi-threaded  application.


Conclusion

  • Multi-Threading Implementation should be proper in the application. 
  • Multi-Threading should not be used in small fast running application.
  • Multi-Thread should be used in big application where the code segment took time to execute.



Share:

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:

Application Insights In Azure

Introduction
  • Application Insights is a Performance Management Service(PMS) for web developers.
  • It keeps track of application performance.
  • It uses powerful analytics tool help us to diagnose the issue.
Application-Insight-Architecture
Application-Insight-Architecture


 How to create Application Insights

Go to Create Resources -> IT &Management Tools->Application Insights



Create-Application-Insights
Create Application Insights

How to set application insights to Web-App

Open the Web App --> Application Insights-->Select the enable option -> Select the App insight if created else select the create new resource-> Click on Apply Button.


See the below image



Configure-Application-Insights
Configure-Application-Insights


Once Configuration is done you can see the telemetry data of Web app will be displayed.


How Web app connected with App-Insights





When ever we create an App insight resource it generate a key called Instrumentation Key.

When we configure the app-insights with web-app then instrumentation key will be added to the application settings of the Web APP, which help to connect both the resources.

Application setting name is APPINSIGHTS_INSTRUMENTATIONKEY and the value is the instrumentation key value.



View Telemetry data


Go to Web app->Application Insights->View Application Insights Data


We can check the below metrics.




  • Live metrics Streams- We can see the live data like Incoming ,outgoing,Overall health of an application.
  • Availability- We can check the availability % of the server.
  • Failure-We can check the failure count and where got failed.
  • Performance-How much time its getting for the server to Get or Post request
  • Alerts  - Generate alert based up on the above matrices and condition , and what action need to be taken if the condition satisfied.
Log-Analytics-Data
Log-Analytics-Data

Benefits


  • Used to Diagnose the issue while running in server.
  • Check the Availability of the application.
  • Check the performance of the application.
  • We get the alert when any changes happen by setting alert condition.
  • Integrate this with all variety of application to check the application health.





Share:

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts