It is very easy to compile a multi-threaded application in. NET and C. Even for beginners who have never used C # To Write multi-threaded applications, follow these simple steps.
Define namespace
In. net, The multithreading function is defined in the system. Threading namespace. Therefore, before using any thread class, you must define the system. Threading namespace. The definition method is as follows:
Using system. Threading;
Start thread
The thread class in the system. Threading namespace represents a thread object. This class object can be used to create new threads, delete, pause, and recover threads. The following code uses the Thread class to create a new thread and then start the thread:
Thread = new thread (New threadstart (writedata ));
Thread. Start ();
Writedata is a function to be executed by this thread. The Code is as follows:
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 ();
}
}
Kill thread
The abort method of the thread class is used to permanently kill a thread. However, before calling the abort method, you must determine whether the thread is still activated, that is, to determine the value of thread. isalive:
If (thread. isalive)
{
Thread. Abort ();
}
Pause a thread
The thread. Sleep method is used to pause a thread for a period of time. The Code is as follows:
Thread. Sleep ();
Set thread priority
We can use the threadpriority attribute of the thread class to set the thread priority. The value range of thread priority is normal, abovenormal, belownormal, highest, or lowest. See the following configuration code:
Thread. Priority = threadpriority. Highest;
Delay thread
The suspend method of the thread class can delay a thread. The thread is delayed until the resume method is called.
If (thread. threadstate = threadstate. Running)
{
Thread. Suspend ();
}
Restore delayed threads
Call the resume method to restore a delayed thread. If the thread is not delayed, the resume method is invalid.
If (thread. threadstate = threadstate. Suspended)
{
Thread. Resume ();
}