Multithreaded Programming Using C#

Introduction

Threading is a lightweight process. With the help of threads we can increase the response time of the application. To use multithreading we have to use the Threading namespace which is included in System. The System.Threading namespace includes everything we need for multi threading. Now lets see the first program.

Program 1

public static void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public static void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
}

public class MyClass {

        public static void Main() {
                Console.WriteLine("Before start thread");

                Thread tid1 = new Thread(new ThreadStart(MyThread.Thread1 ) );
                Thread tid2 = new Thread(new ThreadStart(MyThread.Thread2 ) );

                tid1.Start();
                tid2.Start();
        }
}
This program  has  a   class   MyThread  which  has   two  static  functions  Thread1  and  Thread2.

using System;
using System.Threading;

public class MyThread {

public void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
}

public class MyClass {

        public static void Main() {
                Console.WriteLine("Before start thread");

MyThread thr = new MyThread();

                Thread tid1 = new Thread(new ThreadStart(thr.Thread1) );
                Thread tid2 = new Thread(new ThreadStart(thr.Thread2) );

                tid1.Start();
                tid2.Start();
        }
}
 




Comments