Writing multithreaded application in .NET and C# is pretty easy. This tutorial is for beginners who have not coded any multithreaded application in C# yet. Just follow these simple steps.
Define Namespace
In .NET, threading functionality is defined in System.Threading namespace. So you have to define System.Threading namespace before using any thread classes.
using
System.Threading; Start a Thread The Thread class of 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 Thread.Start method starts the thread.
Thread thread =
new Thread(new ThreadStart( WriteData ));
thread.Start();
Where WriteData is a function which will 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 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 automatically be 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
Thread.Sleep method can be used to pause a thread for a fixed period of time.
thread.Sleep();
Setting Thread Priority Thread class's ThreadPriority property is used to sets thread's priority. The thread priority can have Normal, AboveNormal, BelowNormal, Highest, and Lowest values. These are self-explanatory.
thread.Priority = ThreadPriority.Highest;