Home > DeveloperSection > Blogs > Multithreading in C#

Multithreading in C#


C# C# 
Ratings:
0 Comment(s)
 1669  View(s)
Rate this:

Multithreading in C#

In this blog, I’m trying to explain the concept of multithreading in c#

Multithreading is the ability of an operating system to concurrently run programs that have been divided into subcomponents, or threads. Multithreading contains two or more program codes which run concurrently without affecting to each other and each program codes is called thread.

In .NET framework, System.Threading namespace provides classes and interfaces that enable multi-threaded programming. 

There are two types to create thread in C#, first one is through the Thread Class and second one is through the ThreadStart Delegate.

Example -1                   

Creating Thread with Thread Class

using System;

using System.Threading;

namespace ThreadConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

          Thread t = new Thread(y);

            t.Start();

            for (int i = 0; i < 5; i++)

            {

                Console.WriteLine("X");

            }

        }

        static void y()

        {

            for (int i = 0; i < 5; i++)

            {

                Console.WriteLine("Y");

            }

        }

    }

}

Output

X

X

X

X

X

Y

Y

Y

Y

Example-2

Creating Thread with ThreadStart Delegate

using System;

using System.Threading;

namespace ThreadConsoleApplication3

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread t = new Thread(new ThreadStart(display));

            t.Start();

            for (int i = 0; i < 3; i++)

            {

                Console.WriteLine("Thread A");

            }

        }

        static void display()

        {

            for (int i = 0; i < 3; i++)

            {

                Console.WriteLine("Thread B");

            }

        }

    }

}

Output

Thread A

Thread A

Thread A

Thread B

Thread B

Thread B


Don't want to miss updates? Please click the below button!

Follow MindStick