Friday, May 16, 2008

.Net : Introduction to Multi threading

The basic concept behind multi threading is to perform multiple tasks simultaneously. The success of an application depends on reducing the downtime. For example if the application is performing a lengthy printing task, the application should be in a position to perform other tasks also.

Listing Threads in a Process
using System.Diagnostics;
Process p;
private void Form1_Load(object sender, EventArgs e)
{
p = Process.GetProcessById(5944);
ProcessThreadCollection theTrheads = p.Threads;
foreach (ProcessThread pt in theTrheads)
listBox1.Items.Add(String.Format("{0} {1} {2}", pt.Id, pt.StartTime, pt.PriorityLevel ));
}

A Process is a running application. The above example lists all the threads found in a process whose Process Id is 5944.


The namespace used for creating multi threaded application is System.Threading. The Thread class is used for working with threads.

You create a thread by passing the method to ThreadStart delegate.

Here is a very simple multi threading example which simultaneously shows two messageboxes.

using System.Threading;

Thread t;
Thread t1;
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(Hello));
t.Start();

t1 = new Thread(new ThreadStart(Shalvin));
t1.Start();

}
private void Hello()
{
for (int i = 0; i < 10;i++)
{
MessageBox.Show("Hello");
}
}

private void Shalvin()
{
for (int i = 0; i <10;i++)
{
MessageBox.Show("Shalvin");
}
}
}

Multithreaded Ellipse Application
(Courtesy Saji P Babu)

This example demonstrates Sleep method, suspending and resuming threads. The example simultaneously draws two ellipses in Panel controls.


using System.Threading;

Thread thread;
Thread thread1;
private void Form1_Load(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(DrawEllipse);
thread = new Thread(threadStart);
thread.Start();

ThreadStart threadStart1 = new ThreadStart(DrawEllipse1);
thread1 = new Thread(threadStart1);
thread1.Start();
}
private void DrawEllipse()
{
Graphics g = panel1.CreateGraphics();
Random rnd = new Random();
for (int i = 0; i < 500;i++)
{
g.DrawEllipse(Pens.Blue, 0, 0, rnd.Next(this.Width), rnd.Next(this.Height));
Thread.Sleep(100);
}
}

private void DrawEllipse1()
{
Graphics g = panel2.CreateGraphics();
Random rnd = new Random();
for (int i = 0; i < 500; i++)
{
g.DrawEllipse(Pens.Blue, 0, 0, rnd.Next(this.Width), rnd.Next(this.Height));
Thread.Sleep(100);
}
}
}

No comments:

Post a Comment