Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Thread Concept in C#

Thread Concept in C#:-


A thread is the smallest unit of execution within a process. Each thread has its own stack and local variables. In C#, the main thread is the one that executes the Main method. However, you can create additional threads to run tasks in parallel.

Program
  ↓
Process
  ↓
Threads (lightweight subprocesses)

🔹 What is a Thread?

A thread represents a path of execution inside a program.

  • A process can contain multiple threads

  • All threads share the same memory

  • Each thread has its own stack and execution flow

Example:

  • Main thread → handles UI

  • Background thread → downloads data

  • Another thread → processes data

Multithreading Concept in C#:-

Multithreading is a technique in which a single program (process) is divided into multiple threads that execute concurrently while sharing the same resources.

MultithreadingMultiple threads of one program
MultiprocessingMultiple programs/processes
Multitasking (OS)Multiple applications

Single Program
   ↓
Single Process
   ↓
Multiple Threads (Multithreading)

🔍 Real-Time Application Examples

  • Web servers handling multiple requests

  • Banking transaction systems

  • Video streaming apps

  • Chat applications

  • Games (rendering + input + sound)


The thread has four different states:-

1)  Init State:-  When we create Thread Class Object

2)  Runnable State:-  When we start Thread

3) Waiting State:-  When we use sleep() in Thread

4) End State or Destroy State:-  When the process is completed then the end state


Type of Thread:-

1) Single Threading:- 


If we execute only one program at a time then it is called a single thread

 internal class DemoExample
 {
     public void Display()
     {
         for (int i = 1; i <= 5; i++)
         {
             Console.WriteLine("Non-static method running: " + i);
             Thread.Sleep(500);
         }
     }

     static void Main()
     {
         DemoExample obj = new DemoExample();               // object required
         Thread t = new Thread(obj.Display);  // non-static method

         t.Start();
     }
 }

Call using ThreadStart Delegate

class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample.Display);
            Thread t = new Thread(th);
            t.Start();
            Console.ReadKey();
        }
    }

2) Multi-Threading:- 


Multithreading is a concept in which a single program is divided into multiple threads that execute simultaneously.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample. Display);
            Thread t = new Thread(th);
            t.Start();
            Thread t1 = new Thread(th);
            t1.Start();
            Console.ReadKey();
        }
    }
}



 What Join() Actually Does

Join() makes the calling thread wait until the specified thread completes its execution.

  • It is used for execution order control

  • It is not a general synchronization mechanism

  • It does not synchronize shared data

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample.Display);
            Thread t = new Thread(th);
            t.Start();
            t.Join();
            Thread t1 = new Thread(th);
            t1.Start();
            Console.ReadKey();
        }
    }
}


Thread Synchronization


Thread synchronization is the process of controlling the execution of multiple threads so that shared resources are accessed in a safe and predictable manner.

Thread Synchronization Using lock

🔹 Concept

  • Two threads try to access the same method

  • lock ensures only one thread executes it at a time

What lock Does (Simple Words)

  • Allows only one thread at a time

  • Protects critical section

  • Prevents race condition


using System;
using System.Threading;

class SyncDemo
{
    static object obj = new object(); // lock object

    static void Print()
    {
        lock (obj)   // synchronization
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(
                    Thread.CurrentThread.Name + " : " + i
                );
                Thread.Sleep(500);
            }
        }
    }

    static void Main()
    {
        Thread t1 = new Thread(Print);
        Thread t2 = new Thread(Print);

        t1.Name = "Thread-1";
        t2.Name = "Thread-2";

        t1.Start();
        t2.Start();
    }
}



                       

Post a Comment

0 Comments