Search content within the blog

Thursday, April 23, 2009

Threads in asp.net - Part 1

What are threads?

Each application that is executed has its own 'process space' in the operating system. A Process is an isolated area of memory specifically set aside for that application to be executed in. A Thread on the other hand is a single unit that executes within a process and more specifically by which the operating system allocates processor time. A process will always have at least one thread running in it but it is possible for a process to contain multiple threads that execute simultaneously.

Let me illustrate the difference between a single threaded and a multi threaded application:

Say, for example that you have written a single threaded email client application. This application has only one thread running in its process. When you perform a lengthly operation, such as a 'Send and Receive', because the thread is managing the user interface as well as all the other code, the user has to wait for that operation to complete before they are given back the focus to the user interface.
If it were written as a multi threaded application, the 'Send and Receive' operation could be fired off an a new thread. This would mean that the first thread, that is running the user interface, would still have the focus for the user to interact with as both threads will be running at the same time.

A real life example of this is in Microsoft Outlook. When you click 'Send and Receive' a new thread is started to perform this operation. This allows you to continue to do other things such as compose a new email or view your calendar.

Using threads in this way is an extremely powerful technique. It allows the application to make the best use of the processor's time by running threads in the background in between the application's events.

Example :

using System;
using System.Threading;

public class my3Methods {

public void myMethod1() {
Console.WriteLine("...myThread1 created!");
Thread.Sleep(5000);
Console.WriteLine("...myThread1 has finished!");
}

public void myMethod2() {
Console.WriteLine("...myThread2 created!");
Thread.Sleep(3000);
Console.WriteLine("...myThread2 has finished!");
}

public void myMethod3() {
Console.WriteLine("...myThread3 created!");
Thread.Sleep(1000);
Console.WriteLine("...myThread3 has finished!");
}
}

public class ThreadTest {

public static int Main(String[] args) {

my3Methods testClass = new my3Methods();

Thread myThread1 = new Thread(new ThreadStart(testClass.myMethod1));
myThread1.Start();

Thread myThread2 = new Thread(new ThreadStart(testClass.myMethod2));
myThread2.Start();

Thread myThread3 = new Thread(new ThreadStart(testClass.myMethod3));
myThread3.Start();

return 0;
}
}

No comments:

Post a Comment