I will introduce the thread API in. net, how to use C # To create a thread, start and stop the thread, and set the priority and status.
Programs Written in. net will be automatically assigned a thread. Let's take a look at how to create a thread in C # programming language and continue to learn the thread knowledge. We all know. the main thread of the net runtime environment is started by the main () method, and. net compilation language has an automatic garbage collection function. This garbage collection occurs in another thread. All of this happens in the background, so that we cannot feel what happened. by default, only one thread is used to complete all program tasks, but as we discussed in the first article, we may add more threads as needed to better coordinate the program. For example, in our example, a program with user input that needs to draw graphics or complete a large number of operations, we must add a thread so that user input can be responded in a timely manner, because the input requires time and response, and the other thread is responsible for drawing graphics or a large number of operations.
The system. Threading namespace of the. net base class library provides a large number of classes and interfaces that support multithreading. There are many classes in this namespace. Here we will focus on the Thread class.
The system. Threading. Thread class is the most common class used to create and control a thread, set its priority, and obtain its status. He has many methods. Here we will introduce more common and important methods:
Thread. Start (): the execution of the startup thread;
Thread. Suspend (): suspends a thread, or does not work if the thread has been suspended;
Thread. Resume (): continue the suspended thread;
Thread. Interrupt (): Stop a thread in the wait, sleep, or join thread state;
Thread. Join (): blocks the calling thread until the end of a thread.
Thread. Sleep (): the specified number of milliseconds that will block the current thread;
Thread. Abort (): starts the process of terminating this thread. If the thread is already terminated, the thread cannot be started through thread. Start.
By calling thread. Sleep, thread. Suspend or thread. Join, you can pause or block a thread. Calling the sleep () and suspend () methods means that the thread no longer gets the CPU time. There is a difference between the two methods to suspend a thread. Sleep () causes the thread to stop execution immediately, but before calling the suspend () method, the common language runtime must reach a security point. A thread cannot call the sleep () method for another thread, but can call the suspend () method to suspend the execution of another thread. The thread. Resume () method is called for a suspended thread to continue execution. No matter how many times the suspend () method is used to block a thread, you only need to call the resume () method once to continue the thread execution. Threads that have been terminated and have not started execution cannot be suspended. Thread. Sleep (int x) blocks the thread for X milliseconds. Only when this thread is awakened by other threads by calling the thread. Interrupt () or thread. Abort () method. If a thread is called for a thread in the blocking status. the interrupt () method will change the thread state, but it will throw a threadinterupptedexception exception. You can catch this exception and handle it, or ignore this exception and cause the thread to terminate at runtime. Within a certain period of waiting time, both thread. Interrupt () and thread. Abort () can immediately wake up a thread.
Next we will explain how to abort another thread from one thread. In this case, we can use the thread. Abort () method to permanently destroy a thread and throw a threadabortexception exception. So that the terminated thread can catch exceptions, but it is difficult to control the recovery. The only way is to call the thread. resetabort () to cancel the call, and only when this exception is caused by the call thread. Therefore, thread a can correctly use the thread. Abort () method to act on thread B, but thread B cannot call thread. resetabort () to cancel the thread. Abort () operation. The thread. Abort () method allows the system to quietly destroy threads without notifying users. Once the thread. Abort () operation is implemented, the thread cannot be restarted. The call to this method does not mean that the thread is destroyed immediately. Therefore, to determine whether the thread is destroyed, we can call the thread. join () to determine its destruction, thread. join () is a blocking call and is returned only when the thread is terminated. However, a thread may call the thread. Interrupt () method to stop another thread, which is waiting for the return of the thread. Join () call.
Try not to use the suspend () method to suspend the blocking thread, because it is easy to cause a deadlock. Assume that you have suspended a thread and its resources are required by other threads. What are the consequences. Therefore, we try to assign different priorities to threads of different importance. Use the thread. Priority () method instead of the thread. Suspend () method.
The thread class has many attributes, which must be mastered by multithreaded programming.
Thread. isalive attribute: gets a value that indicates the execution status of the current thread. True if the thread has been started and has not been terminated or aborted; otherwise, false.
Thread. Name attribute: gets or sets the thread name.
Thread. Priority attribute: gets or sets a value that indicates the scheduling priority of the thread.
Thread. threadstate attribute: gets a value that contains the status of the current thread.
In the following example, we will see how to set these attributes. In the following example, we will discuss these attributes in detail.
To create a thread, you must first instantiate a Thread class and call threadstart in the class constructor. This delegate contains where the thread starts execution. After the thread starts, start () starts a new thread. The following is an example program.
Using system;
Using system. Threading;
Namespace learnthreads
{
Class thread_app
{
Public static void first_thread ()
{
Console. writeline ("first thread created ");
Thread current_thread = thread. currentthread;
String thread_details = "thread name:" + current_thread.name +
"/R/nthread state:" + current_thread.threadstate.tostring () +
"/R/n thread priority level:" + current_thread.priority.tostring ();
Console. writeline ("the details of the thread are:" + thread_details );
Console. writeline ("first thread terminated ");
}
Public static void main ()
{
Threadstart thr_start_func = new threadstart (first_thread );
Console. writeline ("creating the first thread ");
Thread fthread = new thread (thr_start_func );
Fthread. Name = "first_thread ";
Fthread. Start (); // starting the thread
}
}
}
In this example, a fthread thread object is created, which is responsible for executing tasks in the first_thread () method. When the thread start () method is called, the proxy containing the first_thread () Address threadstart will be executed.
Thread status
The system. Threading. thread. threadstate attribute defines the State of the thread during execution. A thread must be in one of the statuses from creation to termination. When a thread is created, it is in the unstarted state. The start () method of the thread class changes the thread state to the running state, and the thread will remain in this state, unless we call a method to suspend, block, destroy, or terminate it. If the thread is suspended, it will be in the susponded state, unless we call the resume () method to re-execute it, then the thread will change to the running state again. Once the thread is destroyed or terminated, the thread is in the stopped state. A thread in this state will no longer exist. Just as the thread starts to start, the thread will not be able to return to the unstarted state. The thread also has a background status, which indicates whether the thread runs on the foreground or background. At a specified time, the thread may be in multiple States. For example, if a thread is blocked when sleep is called, and another thread calls the abort method, the thread is in both waitsleepjoin and abortrequested states. Once the thread response is converted into a blocking or abort event, a threadabortexception exception is thrown when the thread is destroyed.
Thread priority
System. Threading. thread. Priority enumerates the priority of a thread, which determines how much CPU time the thread can obtain. High-priority threads usually get more CPU time than general-priority threads. If there are more than one high-priority thread, the operating system will allocate CPU time cyclically between these threads. Low-priority threads get less CPU time. When there is no high-priority thread, the operating system selects the next low-priority thread for execution. Once a low-priority thread encounters a high-priority thread during execution, it will give the CPU to the high-priority thread. The priority of the newly created thread is normal. We can set the priority value of the thread, as shown below:
Highest
Abovenormal
Normal
Belownormal
Lowest
Conclusion: In this section, we discuss the priority of the thread to be created. The system. Threading namespace also contains advanced features such as thread lock, thread synchronization, multi-thread management, and deadlock resolution. We will continue to discuss these features in the following sections.