Multi-threading in C#.Net with step by step code example

Multi-threading in C#.Net with step by step code example

Multi-threading

Is a concept to execute multiple tasks or process simultaneously. Basically multi-threading enables paths to your application to execute multiple processes. Multi-threading can be achieved in C# using System.Threading name space which provides complete control over threading.

Let’s write example code where we will execute two different methods to print numbers using loop and identify the result:

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           //Create thread 1
            Thread threadOne= new Thread(new ThreadStart(OutputOne));
            Thread threadTwo = new Thread(new ThreadStart(OutputTwo));
            threadOne.Start();
            threadTwo.Start();
            Console.ReadKey();
        }

        public static void OutputOne()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("OutputOne is writing : " + i);
            }
        }
        public static void OutputTwo()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("OutputTwo is writing : " + i);
            }
        }
    }
}

Methods

  1. Sleep: method pauses the execution for specific time interval
  2. CurrentThread: provides object of current thread
  3. Start: starts a thread execution
  4. Abort: aborts a thread execution
  5. Suspend: suspends or pauses a thread for given time
  6. Resume: resumes a suspended thread immediately
  7. Join: makes current thread wait for other thread to finish

Properties

  1. Name: get or sets name of a thread
  2. Priority: a property of type System.Threading.ThreadPriority to explicitly set the priority of a thread
  3. IsAlive: returns state of a thread (alive or terminated), its a boolean property
  4. ThreadState: a property of type System.Threading.ThreadState helps retrieving thread state.

Leave a Reply

Your email address will not be published. Required fields are marked *