This chapter will introduce to you. NET thread API, how to create a thread in C #, start and stop threads, set priority and State.
Programs written in. NET are automatically assigned a thread. Let's take a look at the knowledge of creating threads in the C # programming language and continuing to learn threading. We all know that. The main thread of the run-time environment for net runs by the main () method to start the application, and. NET compiled language has automatic garbage collection function, this garbage collection occurs in another thread, all of these are in the background, So we can't feel what's going on. The default is that there is only one thread to complete all the program tasks, but as we discussed in the first article, it is possible that we can add more threads to the program to better coordinate the work as needed. For example, in our case, a program with user input that needs to draw a graph or perform a large number of operations, we have to add a thread to allow the user's input to respond in a timely manner because the input is urgent for the time and response, while the other thread is responsible for drawing or a large number of operations.
the System.Threading namespace of the. NET Base Class Library provides a number of classes and interfaces that support multithreading. There are many classes in this namespace, and we'll focus here on the thread class.
The System.Threading.Thread class is the most common class that creates and controls a thread, sets its priority, and obtains its state. He has a lot of methods, here we will be more common and important methods to do the introduction:
Thread.Start (): Initiates the execution of the thread;
Thread.Suspend (): Suspends the thread, or does not work if the thread is suspended;
Thread.Resume (): continues the suspended thread;
Thread.Interrupt (): Aborts the thread in wait or sleep or join thread state;
Thread.Join (): Blocks the calling thread until a thread terminates
thread.sleep (): Blocks the current thread for the specified number of milliseconds;
Thread.Abort (): To begin the process of terminating this thread. If the thread is already terminating, the thread cannot be started by Thread.Start ().
The thread can be paused/blocked by calling Thread.sleep,thread.suspend or Thread.Join. Calling the sleep () and suspend () methods means that the thread will no longer get CPU time. The two methods of suspending a thread are different, and Sleep () causes the thread to stop executing immediately, but the common language runtime must reach a security point before calling the Suspend () method. One thread cannot call the sleep () method on another thread, but the suspend () method can be called to cause another thread to pause execution. Calling the Thread.Resume () method on a thread that has already been suspended causes it to continue executing. No matter how many times the Suspend () method is used to block a thread, the resume () method is called only once to allow the thread to continue executing. A thread that has been terminated and has not yet started execution cannot use a hang. Thread.Sleep (int x) causes the thread to block x milliseconds. Only if the thread is being called by another thread by calling the Thread.Interrupt () or Thread.Abort () method can it be awakened. If you call the Thread.Interrupt () method on a thread that is in a blocking state, the thread state will change, but the threadinterupptedexception exception will be thrown, you can catch the exception and make the processing, or you can ignore the exception and let the runtime terminate the thread. Within a certain wait time, Thread.Interrupt () and Thread.Abort () can wake up a thread immediately.
below we will show how to abort another thread from one thread. In this case, we can permanently destroy a thread by using the Thread.Abort () method, and the ThreadAbortException exception will be thrown. So that the terminating thread can catch the exception but it is difficult to control the recovery, the only way is to call Thread.resetabort () to cancel just the call, and only if the exception is caused by the calling thread. Therefore, a thread can use the Thread.Abort () method correctly for a B thread, but the B thread cannot call Thread.resetabort () to cancel the Thread.Abort () operation. The Thread.Abort () method allows the system to silently destroy the thread without notifying the user. Once the Thread.Abort () operation is implemented, the thread cannot be restarted. Calling this method does not mean that the thread is destroyed immediately, so in order to determine whether the thread is destroyed, we can call Thread.Join () to determine its destruction, Thread.Join () is a blocking call until the thread does terminate before returning. However, it is possible that one thread calls the Thread.Interrupt () method to abort another thread while the thread is waiting for the return of the Thread.Join () call. do not use the Suspend () method to suspend blocking threads as much as possible, because it is easy to create deadlocks. Suppose you suspend a thread, and the resources of that thread are what the other threads need and what happens. Therefore, we try to give different priorities to threads of different importance, using the Thread.priority () method instead of the Thread.Suspend () method.
The thread class has a lot of attributes, and these are important attributes that we have to master for multithreaded programming.
Thread.isalive Property: Gets a value that indicates the execution state of the current thread. True if this thread has started and has not been terminated or aborted properly; otherwise, false.
Thread.Name Property: Gets or sets the name of the thread.
Thread.priority Property: Gets or sets a value that indicates the scheduling priority of the thread.
Thread.threadstate Property: Gets a value that contains the state of the current thread.
In the example below, we'll look at how to set these properties, which we'll discuss in detail in the following example.
To create a thread, you first have to instantiate one of the thread classes and invoke ThreadStart delegation in the class constructor. This delegation contains where the thread starts executing. When the thread starts, the start () method starts a new thread. Here is an example program.
usingSystem;usingSystem.Threading;namespacelearnthreads{classthread_app{ Public Static voidFirst_thread () {Console.WriteLine ("First thread created"); Thread Current_thread=Thread.CurrentThread;stringThread_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 is:"+thread_details); Console.WriteLine ("First thread terminated");} Public Static voidMain () {ThreadStart Thr_start_func=NewThreadStart (First_thread); Console.WriteLine ("Creating The first thread"); Thread Fthread=NewThread (thr_start_func); Fthread.name="First_thread"; Fthread.start ();//starting the thread}}}
in this example, a Fthread thread object is created, and the thread is responsible for performing the tasks inside the First_thread () method. When the Start () method of the Thread is called, the agent that contains the address of the first_thread () ThreadStart will be executed.
Thread status
system.threading.thread.threadstate property defines the state of the thread at execution time. When a thread terminates from creation to thread, it must be in one of the states. When the thread is created, it is in unstarted State, thread class start () The running state, and the thread will remain in this state unless we call the appropriate method to suspend, block, destroy, or terminate it naturally. If the thread is suspended, it will be in the suspended state unless we call resume () method to make it re-executed, and the thread will change to running status. Once the thread is destroyed or terminated, the thread is in the stopped state. The thread in this state will no longer exist, just as the thread starts, and the thread will not be able to return to the unstarted state. The thread also has a background state, which indicates whether the thread is running in the foreground or in the background. At a certain time, the thread may be in more than one state. As an example, a thread is blocked by calling sleep, and then another thread calls abort method to this blocked thread, when the thread is at the same time waitsleepjoin and abortrequested status. Once the thread responds to sle is blocked or aborted, the threadabortexception exception is thrown when destroyed.
Thread Priority
System.Threading.Thread.Priority enumerates the priority levels of a thread, which determines how much CPU time the thread can get . High-priority threads typically get more CPU time than normal-priority threads , and if more than one high-priority thread, the operating system will cycle the CPU time between those threads . Low-priority threads get relatively little CPU time, and when there are no high-priority threads, the operating system picks the next low-priority thread to execute. Once a low-priority thread encounters a high-priority thread at execution time, it yields the CPU to the high-priority thread. The newly created thread priority is the general priority, and we can set the value of the thread's priority level, as shown here:
Highest AboveNormal Normal belownormal Lowest
. NET multithreaded Programming (2)-thread class