Like java, writing a multi-threaded application in c # is very simple. This chapter describes how to develop multi-threaded programs in c. In. net, threads are defined by the System. Threading namespace. Therefore, you must include this namespace.
Using System. Threading;
Start a thread
The thread class in the System. Threading namespace describes a thread object. By using a class object, you can create, delete, stop, and restore a thread. Create a new thread and start the thread through the new operation.
Thread = new Thread (new ThreadStart (HelloWorld ));
Thread. Start ();
Note: Unlike java programs, after creating a new thread and calling the start () method, it does not call the run () method, but passes the thread call program.
The following are the functions executed by the startup thread:
Protected void HelloWorld ()
{
String str;
Console. write ("helloworld ");
}
}
Killing a thread
The Abort () method of the thread class can permanently kill a thread. Before killing a thread, you should determine whether the thread is in the active state.
If (thread. IsAlive)
{
Thread. Abort ();
}
Stop a thread
The Thread. Sleep method can stop a Thread in a fixed cycle class.
Thread. Sleep ();
Set thread priority
The ThreadPriority attribute in the Thread class is used to set the priority of a ThreadPriority. The thread priority levels include Normal, AboveNormal, BelowNormal, Highest, and Lowest.
Thread. Priority = ThreadPriority. Highest;
Suspends a thread
Calling the Suspend () method of the thread class suspends a thread until it is invoked using the Resume () method. Before a thread is suspended, determine whether the thread is in the active state.
If (thread. ThreadState = ThreadState. Running)
{
Thread. Suspend ();
}
Call a thread
The Resume () method can be used to call up a suspended thread. Before suspending a thread, you should determine whether the thread is in the suspension period. If
The method does not work if the thread is not suspended.
If (thread. ThreadState = ThreadState. Suspended)
{
Thread. Resume ();
}