Click here to Skip to main content
Click here to Skip to main content

Understanding Traditional Threading in C#

, 17 Feb 2014
Rate this:
Please Sign up or sign in to vote.
Here I will discuss the concepts of threading / multi-threading in C# using program.

Introduction

Here I will discuss the concepts of threading / multi-threading in C# using program. I would recommend that you should copy the given programs in your Visual Studio and run the program after making changes as you wish to see its impact. For example, if you have doubts about whether a method invoked by thread can return some value or not, just modify the return type of the method accordingly. Compile, run the program. You will get your answers while compiling or running the program. It will help you not only to understand the concepts but remember as well.

using System;

namespace TestConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
            var traditionalThread = new TraditionalThread();
            traditionalThread.TestTraditionalThreadWithoutParameters();
            traditionalThread.TestTraditionalThreadWithParameters();
            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Threading;

namespace TestConsole
{
    public class TraditionalThread
    {
        public void TestTraditionalThreadWithoutParameters()
        {
            Console.WriteLine("Testing threads with methods not having parameter");
            var threads = new List<Thread>
                              {
                                  new Thread(PrintNumbers),
                                  new Thread(new ThreadStart
                                  (PrintNumbers)), //Use ThreadStart when method has no parameter
                                  new Thread(PrintNumbers),
                                  new Thread(() => Console.WriteLine
                                  ("You can use lambda expression or anonymous methods as well"))
                              };
            threads.ForEach(t => t.Start()); //Start all the threads
            threads.ForEach(t => t.Join()); //If you omit this line, program will exit 
            		// without completing PrintNumbers since main thread will not wait.
        }

        public void TestTraditionalThreadWithParameters()
        {
            Console.WriteLine("Testing threads with methods having parameter");
            var threads = new List<Thread>
                              {
                                  new Thread(new ParameterizedThreadStart
                                  (PrintParticularCharacter)), //User 
                                  // ParameterizedThreadStart when method has parameter
                                  new Thread((toPrint) =>
                                                 {
                                                     for (var count = 0; count < 10; count++)
                                                         Console.WriteLine("ThreadId : {0}  and Value : {1}",
                                                            Thread.CurrentThread.ManagedThreadId, toPrint);
                                                 })
                              };
            threads[0].Start("X");
            threads[1].Start("Y");
            threads.ForEach(t => t.Join()); //If you omit this line, 
            // program will exit without completing PrintNumbers since main thread will not wait.
        }

        private static void PrintNumbers() //Must return void if invoked by thread using ThreadStart
        {
            for (var count = 0; count < 10; count++)
            {
                Console.WriteLine("ThreadId : {0} 
                	and Value : {1}", Thread.CurrentThread.ManagedThreadId, count);
                Thread.Sleep(1000); //Sleep for 1 sec. It will not consume CPU cycle.
            }
        }

        private static void PrintParticularCharacter(object toPrint)  //Must return void and 
        	//parameter type must be object if invoked by thread using ParameterizedThreadStart
        {
            for (var count = 0; count < 10; count++)
            {
                Console.WriteLine("ThreadId : {0}  
                	and Value : {1}", Thread.CurrentThread.ManagedThreadId, toPrint);
                Thread.Sleep(1000); //Sleep for 1 sec
            }
        }
    }
}

Below are some terms/concepts you must know.

Thread.Sleep

You can call this method on any thread object. It makes that thread sleep for a given time period. It accepts time period in milliseconds. It does not consume CPU cycles while sleeping.

Example
t1.sleep(1000); // It will make thread t1 to sleep for 1 second.

Thread.Join

You can call this method on any thread object. It makes the parent thread wait for the child thread. The main/parent thread will wait for the child thread to complete.

Example
t1.Join();    //Main thread will wait for thread t1 to complete.
t2.Join(2000);    //Main thread will wait for thread t2 for 2 seconds to complete. 
	// After 2 seconds, main thread will start processing next statements.

Background and Foreground Threads

By default, threads you create explicitly are foreground threads. Foreground threads keep the application alive for as long as any one of them is running, whereas background threads do not. Once all foreground threads finish, the application ends, and any background threads still running abruptly terminate.

You can check if the thread is a background thread or foreground thread by using thread’s property “IsBackground”.

Thread Pooling >>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adarsh Chaurasia (Consultant|Mentor|Tech Savvy)
Software Developer (Senior)
India India
I have 4.6+ years of experience in SaaS, SOA based Enterprise Web Application design and development using Microsoft technology stack. I have mostly worked on Business layer, Data access layer, WCF, Entity Framework, Microsoft Application Blocks, Search engines, APIs integration, Third party APIs/Product Research & Development.
 
I am a huge fan of Design Patterns. I also work as Software Consultant. I read/write blogs, help and learn from other developers.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 PinmemberMember 1016653318-Feb-14 21:02 
GeneralRe: My vote of 1 PinmemberAdarsh Kumar Chaurasia18-Feb-14 21:53 
GeneralRe: My vote of 1 PinmemberMember 1016653318-Feb-14 23:07 
Question[My vote of 2] My vote of 2 Pinmemberkartelo17-Feb-14 23:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 17 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia (Consultant|Mentor|Tech Savvy)
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid