C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Creating threads and determining when a thread ends


Posted Date: 15 May 2004    Resource Type: Articles    Category: .NET Framework

Posted By: ANITA MARY JOSEPH       Member Level: Gold
Rating:     Points: 15



NOTE : Kindly go through my article titled "Introducing Multithreaded Programming in C# " before going through this one

Creating Multiple Threads

You can create as many threads in your program, check out the example below

Example 1

//Creating Multiple Threads

using System;
using System.Threading;

class MyThread
{
public int count;
public Thread thread;

public MyThread(string name)
{
count = 0;
thread = new Thread(new ThreadStart(this.run));
thread.Name = name;
thread.Start();
}

//Entry point of thread.
void run()
{
Console.WriteLine(thread.Name + " starting.");
do
{
Thread.Sleep(500);
Console.WriteLine("In " +thread.Name + ",count is " +count);
count++;
}while(count < 10);

Console.WriteLine(thread.Name + " treminating.");
}
}

class CreateMoreThreads
{
public static void Main()
{
Console.WriteLine("Main thread starting.");

// First, construct a MyThread object.
MyThread myThread1 = new MyThread("child #1");
MyThread myThread2 = new MyThread("child #2");
MyThread myThread3 = new MyThread("child #3");

do
{
Console.Write(".");
Thread.Sleep(100);
}while (myThread1.count < 10 || myThread2.count < 10 || myThread3.count < 10);

Console.WriteLine("Main thread ending.");
Console.Read();
}
}


Run the program. As you can see, once started, all three threads share the CPU.
- - -

Determining When a Thread Ends

Often it is useful to know when a thread has ended. Fortunately, Thread provides two means by which you can determine whether a thread has ended.

One way is By the IsAlive property. It is defined like this:

public bool IsAlive {get;}


IsAlive returns true if the thread upon which it is called is still running. It returns false otherwise.

Example

replace the do while loop in the Main() Function shown in Example 1 with the following code:

do
{

//code

} while (myThread1.thread.IsAlive &&
myThread2.thread.IsAlive &&
myThread3.thread.IsAlive);


Another way to wait for a thread to finish is to call Join().

Join() waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. A ThreadStateException will be thrown if the thread has not been started. Additional forms of Join() allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate.

Example

replace the Main() Function in Example 1 with following code

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

// First, construct a MyThread object.
MyThread myThread1 = new MyThread("child #1");
MyThread myThread2 = new MyThread("child #2");
MyThread myThread3 = new MyThread("child #3");

myThread1.thread.Join();
Console.WriteLine("Child #1 joined.");

myThread2.thread.Join();
Console.WriteLine("Child #2 joined.");

myThread3.thread.Join();
Console.WriteLine("Child #3 joined.");

Console.WriteLine("Main thread ending.");
Console.Read();
}

Run the program and view the output, As you can see, after the calls to Join() return, the threads have stopped executing.

- - - -

The IsBackground Property

By default, a thread is created as a foreground thread. It can be changed to a background thread by using the IsBackground property defined by Thread as shown here:

public bool IsBackground { get; set;}

To set a thread to background, simply assign IsBackground a true value. A value of false indicates a foreground thread.

- - - -

Thread Priorities

Each thread has a priority setting associated with it. A thread’s priority determines, in part, how much CPU time a thread receives. In general, low-priority threads receive little CPU time. High priority threads receive a lot.

It is important to understand that factors other than a thread’s priority can also affect how much CPU time a thread receives. For example, if a high-priority thread is waiting on some resource, perhaps for keyboard input, it will be blocked, and a lower-priority thread will run. Thus, in this situation a low-priority thread may gain greater access to the CPU than the high-priority thread over a specific period.

When a child thread is started, it receives a default priority setting. You can change a thread’s priority through the Priority property, which is a member of Thread. This is its general form:

public ThreadPriority Priority{ get; set; }


ThreadPriority is an enumeration that defines the following five priority settings:



ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest


The default priority setting for a thread is ThreadPriority.Normal

Example

//Setting Priorities for threads
myThread1.thread.Priority = ThreadPriority.AboveNormal;
myThread2.thread.Priority = ThreadPriority.BelowNormal;





Responses

Author: Charlie Arruda    15 Jun 2004Member Level: Bronze   Points : 0
That was a well written description! Thanks!


Author: Ravi Makwana    10 Jan 2005Member Level: Bronze   Points : 0
This is a winner article.
Good job.

Regards,


Author: Samuel    18 May 2005Member Level: Bronze   Points : 0
I was browsing through the book " C# The Complete Reference" by Herbert Schildt, and realized that the article contents and the examples were taken from this book. So in case anyone feels like geting more details about concept of multithreading refer to the above book, Chapter 21. This article is a complete take off from this book.



Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Determining thread termination  .  Determining thread endings  .  Determine when threads stop  .  Creating threads in C#  .  Creating and Stopping threads  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Introducing Multithreaded Programming in C#.
Previous Resource: Completely Customized Menu Procedures for .NET
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

doors in nj

Contact Us    Privacy Policy    Terms Of Use