Wednesday, October 10, 2007

Multithreading Using C#


Multithreading has always been a helpful friend of a programmer . Multithreading increases the response time of an application .  Multithreading can be implemented by using namespace system.threading  .

Why Multithreading is required ?

> For this I will give U a simple example : Assume U have a company and U have only one assistance and 0 workers then what will happen the complete workload of company will be on your assistance , the assistance then take much time to do everything one by one , Which will affect U in turn .. your application also runs in the same manner if U have only single thread Your execution and your processing will be very slow which may also hangs your application . So Multithreading distributes specified process to run in another thread  an wont affect the normal processing of your application ..

Lets have a little demo for this .

Demo - 1


using System;
using System.Threading;
public class MyThread
    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));

Explanation :

In this Demo u have 2 static methods Thread1 and Thread2 . To make a thread we are making a object class named Thread.

The constructor of this class takes a reference of a ThreadStart class. This constructor
can send two types of exceptions; ArgumentNullException when the parameter is
a null reference or a Security Exception when program does not have permission to
create thread.


The parameter of the Thread class is reference to a ThreadStart class.
ThreadStart class points to the method that should be executed first when a
thread is started. The parameter is the name of the function, which is considered as
a thread function. Thread1 is a static function so we give it with the name of class
name without making an object of the class. The thread starts execution with
Start() method of the Thread class. The output of this program is

Before start thread
Thread1 0
Thread1 1
Thread1 2
Thread1 3
Thread1 4
Thread1 5
Thread1 6
Thread1 7
Thread1 8
Thread1 9
Thread2 0
Thread2 1
Thread2 2
Thread2 3
Thread2 4
Thread2 5
Thread2 6
Thread2 7
Thread2 8
Thread2 9

This is how we using multithreading in our application ...

Technorati Tags: , ,