Working with threads in C# - Part 2

Naimishforu
Posted by in C# category on for Beginner level | Points: 300 | Views : 14960 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article we shall see the C# threading model and we shall also see how to work with threads in C#.NET

Introduction


To demonstrate, let's create a new class, whose Main method starts the new thread, which invokes an implementing method. 

Any multitasking service or application you create will use classes from the System.Threading namespace, so this, as well as the general System namespace, should be specified at the start of your code.

using System;
using System.Threading;

namespace ThreadExample
{
  class ThreadExample
  {
  }
}

The next section of code defines the implementing method that will be delegated to the background thread.

This code now defines the Main method, the program entry point.

In this code, the ThreadStart delegate is called. ThreadStart is used to create a new thread and specifies the method that the thread will use. In this case, it's the BackgroundThreadMethod.

This code creates the new thread, t.

And the thread is started with the Start method of the Thread class.

static void BackgroundThreadMethod()
{
  Console.WriteLine("background thread started");
}

static void Main(string[] args)
{
  //declare threadstart delegate
  ThreadStart background = new ThreadStart(BackgroundThreadMethod);
  Console.WriteLine("Creating background thread");
  //start background thread
  Thread t = new Thread(background);
  t.Start();
  Console.WriteLine("Starting background thread");
}

The code output displays, with the program alternating between each thread.

In this example, there are two delegated methods. The first method counts numbers up, the other counts numbers down.

static void Main(string[] args)
{
  //declare threadstart delegates
  ThreadStart count = new ThreadStart(CountMethod);
  Console.WriteLine("Creating count thread");

  ThreadStart countdown = new ThreadStart(CountDownMethod);
  Console.WriteLine("Creating countdown thread");
}

As CountMethod finishes each loop, it pauses for a short time to allow other threads to execute. This will use the Thread.Sleep method, a static method that suspends the current thread for the specified number of milliseconds.

static void CountMethod()
{
  for (int i = 1; i < 10; i++)
  {
    Console.WriteLine("{0}:Count:{1}", Thread.CurrentThread.Name, i);
    Thread.Sleep(500);
  }
}

In the Main method, you create ThreadStart delegates for both methods and pass them to two new threads, t1 and t2. These threads are then started.

static void Main(string[] args)
{
  //declare threadstart delegates
  ThreadStart count = new ThreadStart(CountMethod);
  Console.WriteLine("Creating count thread");

  ThreadStart countdown = new ThreadStart(CountDownMethod);
  Console.WriteLine("Creating countdown thread");

  //start background thread
  Thread t1 = new Thread(count);
  t1.Name = "thread 1";
  t1.Start();
  Console.WriteLine("Starting {0}", t1.Name);
  Thread t2 = new Thread(countdown);
  t2.Name = "thread 2";
  t2.Start();
  Console.WriteLine("Starting {0}", t2.Name);
}

The system will usually switch rapidly between all active threads, so it appears that they are running at the same time. Sometimes, however, the operation of one thread will depend on another thread finishing first. In this situation, you should attach the second thread to the first.

This joins the active thread, the Main method, to the end of thread 1, so the first thread must be completed before the Main method will continue.

//main method process
for (int i = 1; i < 10; i++)
{
  Console.WriteLine("Main Method: {0}", i);
  Thread.Sleep(500);
}
//wait for thread 1 to stop
t1.Join();
Console.WriteLine("Thread 1 has finished processing!!!")

Another way of changing the order in which threads are executed is to use the Suspend method. This method pauses the thread indefinitely.

Threads paused with the Suspend method must be woken by calling the Resume method.

//suspend thread
t3.Suspend();
Console.WriteLine("Thread 3 suspended. Hit Return to Continue");
//resume thread
Console.ReadLine();
t3.Resume();
Console.WriteLine("Thread 3 resumed");
//wait for thread 3 to stop
t3.Join();
Console.WriteLine("Thread 3 has finished processing!!!");
You can stop a thread while it is executing with the Interrupt method. This causes the thread to throw a ThreadInterruptedException exception.

//start new background thread
Thread t4 = new Thread(countdown);
t4.Name = "thread 4";
t4.Start();
Console.WriteLine("Starting {0}", t4.Name);
//interrupt thread
t4.Interrupt();

This exception can then be handled inside a catch clause to free up resources if necessary.

static void CountDownMethod()
{
  try
  {
    for (int i = 10; i >= 0; i--)
    {
    Console>writeLine("{0}:CountDown:{1}",Thread.CurrentThread.Name,i);
    Thread.Sleep(500);
    }
  }
  catch (ThreadInterruptedException tie)
  {
    Console.WriteLine("Thread{0}interrupted",Thread.CurrentThread.Name);
  }
  finally
  {
    Console.WriteLine("Thread{0} exiting",Thread.CurrentThread.Name)
  }
}

A thread may also be aborted. The Abort method will cause the thread to throw a ThreadAbortException exception. This exception can not be handled in a catch block, but code contained in the finally block will execute and can be used to clean up.

//start new background thread
Thread t5 = new Thread(count);
t5.Name = "thread 5";
t5.Start();
Console.WriteLine("Starting {0}", t5.Name);
//abort thread
t5.About();

Thanks and Have fun!!!!!

Page copy protected against web site content infringement by Copyscape

About the Author

Naimishforu
Full Name: Naimish Pandya
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/22/2011 7:38:35 AM
Country: India
Thanks, Naimish http://dotnetinterview.zxq.net/ http://naimishpandya.blogspot.in/
http://naimishpandya.blogspot.in/

Login to vote for this post.

Comments or Responses

Posted by: Tripati_tutu on: 3/25/2011 | Points: 25
Nice one...
Posted by: Naimishforu on: 3/25/2011 | Points: 25
Thanks :)

Login to post response

Comment using Facebook(Author doesn't get notification)