Writing multithreaded applications in .NET and C# is quite easy. This tutorial is for those beginners that have not yet coded any multithreaded applications in C#. Just follow this simple procedure.
Define Namespace
In .NET, threading functionality is defined in the System.Threading namespace. So you have to specify the System.Threading namespace before using any thread classes as in the following:
using System.Threading;
Start a Thread
The Thread class of the System.threading namespace represents a Thread object. By using this class object, you can create new threads, delete, pause, and resume threads. The Thread class creates a new thread and the Thread.Start method starts the thread.
Thread thread = new Thread(new ThreadStart( WriteData ));
thread.Start();
Where WriteData is a function to be executed by the thread.
protected void WriteData()
{
string str ;
for ( int i = 0; i<=10000; i++ )
{
str = "Secondary Thread" + i.ToString();
Console.WriteLine(listView1.ListItems.Count, str, 0, new string[]{""} );
Update();
}
}
Aborting a Thread
The Thread class's Abort method is called to abort a thread. Make sure you call IsAlive before Abort.
if ( thread.IsAlive )
{
thread.Abort();
}
Note: When a call is made to the "Abort" method to destroy a thread, the Common Language Runtime (CLR) throws a "ThreadAbortException". ThreadAbortException is a special exception that can be caught, but it will be automatically raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before killing the thread. Since the thread can do an unbounded computation in the finally blocks, you must call the "Join" method to guarantee that the thread has died. Join is a blocking call that does not return until the thread actually stops executing.
Pausing a Thread
The Thread.Sleep method can be used to pause a thread for a fixed period of time.
thread.Sleep();
Setting Thread Priority
A Thread class's ThreadPriority property sets the thread's priority. The thread priority can have "Normal", "AboveNormal", "BelowNormal", "Highest", and "Lowest" values. These are self-explanatory.
thread.Priority = ThreadPriority.Highest;
Suspend a Thread
The Suspend method of the Thread class suspends a thread. The thread is suspended until the Resume method is called.
if (thread.ThreadState == ThreadState.Running )
{
thread.Suspend();
}
Resume a suspended Thread
The Resume method is called to resume a suspended thread. If a thread is not suspended then the Resume method will have no affect.
if (thread.ThreadState == ThreadState.Suspended )
{
thread.Resume();
}
Note
This article was originally written in 2001 using .NET 1.0. Things have changed since then. Here are some updated recommended readings on this topic: