Multi-threaded Programming in C#

In the earliest days of programming, computing machines were single-core and processor could execute only single set of instructions at a time. Therefore, the program used to execute in a sequential manner where the instructions that came first in the code were executed first and so on. This programming paradigm is known as single threaded programming. A thread is basically smallest unit of execution.

Multi-threaded programming, on the other hand, depicts a programming phenomena where multiple program instructions run in parallel. Due to dual-core and quad-core processors, we are now able to implement multi-threaded programming in real sense.

In C#, threading is implemented via <Thread class which belongs to System.Threading namespace. The object of the Thread class takes a function as parameter. When the Start function is called on this Thread object, the function that is passed to the Thread object starts executing in Parallel. Have a look at the following example to grasp the concept.

´╗┐using System;
using System.Threading;

namespace CSharpTutorials{
    class Tutorial {
        static void Main() {
            Thread newthread = new Thread(ThreadFunction);
            newthread.Start();// Function starts executing in parallel here.

            for (int i = 1; i <= 100; i = i + 2) {
                //function prints odd numbers less than 100;
                Console.Write(" "+i);
            }
            Console.ReadKey();
        }

        public static void ThreadFunction() {
            for (int i = 0; i <= 100; i = i + 2) {
                // function prints even numbers up to 100
                Console.Write(" "+i);
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a function named ThreadFunction has been created which displays the even numbers from 0 to hundred. Inside the Main function a thread object newthread has been created and in the constructor of the object, the Thread function has been passed. Next, Start method has been called upon this object. At this point, two set of instructions start executing in parallel: One is the code in the main method and the other is the code inside the ThreadFunction.The main method starts printing the odd number while the ThreadFunction starts printing the even function. In the output, you will see odd and even numbers printed randomly. When the Main function gets the console, odd numbers will be printed and when ThreadFunction gets the console. even numbers shall be printed.

<<< Stacks & Queues in C#Dictionaries in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .