Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    API(s)
    Sencha-Touch
    Single Page App
    Bootstrap
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> C# >> Threading in C# with Example
Threading in C# with Example
Threading in C# with Example


by Arun Singh on 8/29/2011 9:54:46 PM

Views: 28245       Comments: 2

Threading in C# with Example

C# supports parallel execution of job or program code through multithreading. Multithreading contains two or more program codes which run concurrently without affecting to each other and each program codes is called thread. Use System.Threading namespce to implement multithreading in your program. Let’s see a simple example of creating multithreading in c sharp.

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: Creating thread with help of Thread class

Here I am creating two threads which are executes concurrently without effecting to each other, first thread is main thread which prints ‘Thread: A ‘message and second one is ThreadB which prints ‘Thread: B’ message.

using System.Threading;

 

namespace ThreadTest

{

    class Program

    {

        static void Main(string[] args)

        {

            //Creating thread object to strat it

            Thread th = new Thread(ThreadB);

            Console.WriteLine("Threads started :");

            // Start thread B

            th.Start();

            //Thread A executes 10 times

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

            {

                Console.WriteLine("Thread : A");

            }

           

            Console.WriteLine("Threads completed");

            Console.ReadKey();

        }

        public static void ThreadB()

        {

           //Executes thread B 10 times

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

          {

             Console.WriteLine("Thread : B");

          }

        }

    }

}

Output:

Threading in C# with Example

Example: Creating thread with help ThreadStart Delegate.

When a managed thread is created, then method that executes within thread is represented by the ThreadStart delegate and passed into Thread constructor.  That is ThreadStart delegate represent a method which used in thread execution.

Let’s see the brief description of creating thread with help of ThreadStart delegate.

Example:

using System.Threading;

 

namespace ParameterizedThread

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create Thread class object and paas object of ThreadStart delegate with specified method its constructor

            Thread th =new Thread(new ThreadStart(MyMethod));

            th.Name = "Child thread";

            // Start child thread

            th.Start();

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

            {

                Console.WriteLine("Main Thread");

            }

            Console.WriteLine("End Thread...");

            Console.ReadKey();

        }

        // Method used in thread execution

        public static void MyMethod()

        {

           

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

            {

                Console.WriteLine("Child Thread");

            }

 

        }

    }

}

 

Output:

Threading in C# with Example

Example: Create thread with taking parameter or Parameterized Thread.

We can also create parameterized thread for creating parameterized thread writes the following code.

using System.Threading;

 

namespace ParameterizedThread

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create object of ParameterizedThreadStart to create parameterized thread 

            ParameterizedThreadStart paraThread = new ParameterizedThreadStart(MyMethod);

            // Paas the object ParameterizedThreadStart in Thread constructor 

            Thread th = new Thread(paraThread);

            // Assign name of thread

            th.Name = "Child Thread";

            Console.WriteLine("Start thread...");

            //Pass the parameter into child thread

            th.Start(th.Name);

            // Execute the main thread

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

            {

                Console.WriteLine("Main Thread");

            }

            Console.WriteLine("End Thread...");

            Console.ReadKey();

        }

        public static void MyMethod(object obj)

        {

            string name = Convert.ToString(obj);

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

            {

                Console.WriteLine(name);

            }

 

        }

    }

}

Output:

Threading in C# with Example

Thread Priority:

Thread priority specifies the scheduling priority of thread, and the executions of threads perform on its priority basis. When we create any thread and not assign its priority then by default normal priority will be assign for it. The thread priority does not affect the state of thread.

Example: Let’s see a brief example of thread priority.

using System.Threading;

 

namespace ForegroundThread

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create ThreadA object

            Thread threadA = new Thread(new ThreadStart(ChildThreadA));

            // Create ThreadB object

            Thread threadB = new Thread(new ThreadStart(ChildThreadB));

 

            threadA.Name = "Thread A";

            threadB.Name = "Thread B";

            // set highest priority of threadB

            threadB.Priority = ThreadPriority.Highest;

            threadA.Start();

            threadB.Start();

            Thread.CurrentThread.Name = "Main";

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

            {

                Console.WriteLine(Thread.CurrentThread.Name);

            }

            Console.ReadKey();

       }

        public static void ChildThreadA()

        {

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

            {

                Console.WriteLine("Child thread A:");

            }

        }

        public static void ChildThreadB()

        {

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

            {

                Console.WriteLine("Child thread B:");

            }

        }

    }

}

Output:

Threading in C# with Example

Report Abuse Form
Reason:    
 


Threading in C# with Example
by Amit Singh 9/28/2011 1:54:57 AM
This one nice article!
Report Abuse

Re: Threading in C# with Example
by Arun Singh 9/29/2011 1:27:28 AM
thanks Amit singh !!!!!!!
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Arun SinghRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 4792
Advertisement
MindStick DataConver
Advertise with Us
  
Copyright © 2014MindStick. All Rights Reserved.