. Multi-threaded programming under net

Source: Internet
Author: User
Tags object end net sleep terminates thread thread class time limit
Multithreading is a lot of control system has the characteristics, it can greatly improve the operation of the program efficiency, so multithreaded programming skills for programmers throughout the concern. In front of Microsoft. NET strategy is further advanced, a variety of coherent skills are being accepted by the grand programmers, the same. NET Multithread programming technology has ...

Multithreading is a lot of control system has the characteristics, it can greatly improve the operation of the program efficiency, so multithreaded programming skills for programmers throughout the concern. In front of Microsoft. NET strategy is further advanced, a variety of coherent skills are being accepted by the grand programmers, the same. NET multithreaded programming technology has the most important position. This article I will introduce to the public in. NET, the basic methods and procedures for multithreaded programming. Start a new thread in the. NET setting up a new thread is often easy, you can start a new thread with the following statement: Threadthread=newthread (Newthreadstart (ThreadFunc)); Start (); First, the statement establishes a new thread object and indicates a method for that thread. When a new thread starts, the method is called to execute. The thread object passes through a system.. An instance of the Threading.threadstart class invokes the threading method it wants to invoke in a type-safe way. The second statement formally starts the new thread, and once the method start () is invoked, the thread is maintained in a "Alive" state, and you can determine whether it is in the "Alive" state by reading its IsAlive property. The following statement shows how to suspend a thread if it is in a "alive" state: if (thread). IsAlive) {thread. Suspend ();} However, notice that the start () method of the thread object simply starts the thread without guaranteeing that its threading method ThreadFunc () can be executed immediately. It only guarantees that the thread object can be assigned to CPU time, and the actual execution is determined by the control system according to the processor time. A thread's approach does not imply any arguments, nor does it return any values. Its naming rules are the same as those for general functions. It can be static as well as static (nonstatic). When it completes, the corresponding thread ends, and the IsAlive property of its thread object is set to False. The following is an instance of a threading approach: Publicstaticvoidthreadfunc () {for (inti=0;i%26lt;10;i++) {Console.WriteLine ("threadfunc{0}" i);} foreground thread and backer thread. NET Common language runtime (COMMONLANGUAGERUNTIME,CLR) can divide threads of two types of differences: foreground and backer threads. The distinction between the two is that an application must run a foreground thread of all facets to exit, and for a backer thread, the application can simplyExit, full backer thread when the application exits the city automatically ends. Whether a thread is a foreground thread or a backer thread can be determined by its IsBackground attribute. This property is readable and writable. Its default value is false, meaning that a line Cheng feel the foreground thread. We can set its IsBackground property to true to make it a backer thread. The following example is an effective supervisor program that starts with 10 threads per thread and runs for 5 seconds at a time. Because the thread's IsBackground attribute defaults to False, that is, they are both foreground threads, so even though the main thread of the program is finished quickly, the program ends up running until the fully-started threads run. The sample code is as follows: Usingsystem;usingsystem.threading;classmyapp{publicstaticvoidmain () {for (inti=0;i%26lt;10;i++) { Threadthread=newthread (Newthreadstart (threadfunc)), Thread. Start ();} Privatestaticvoidthreadfunc () {datetimestart=datetime.now;while (Datetime.now-start). SECONDS%26LT;5);} Next we make a slight modification to the code above to set the IsBackground property of each thread to true, and each thread is a backer thread. So as long as the main thread of the program is over, the whole program is over. The sample code is as follows: Usingsystem;usingsystem.threading;classmyapp{publicstaticvoidmain () {for (inti=0;i%26lt;10;i++) { Threadthread=newthread (Newthreadstart (threadfunc)), Thread. Isbackground=true;thread. Start ();} Privatestaticvoidthreadfunc () {datetimestart=datetime.now;while (Datetime.now-start). SECONDS%26LT;5);} So how do we know how to set the IsBackground property of a thread, given the difference between the foreground thread and the backer thread? Here are some basic principles: for some threads running on a backer, when the program ends thisSome threads are not necessarily running, so these threads should be set up as a backer thread. A program, for example, initiates a thread that carries out a number of operations, but as soon as the program is finished, the thread loses its constant meaning, and that thread is supposed to be a backer thread. Some threads that serve the user interface are frequently set up as foreground threads, because even though the main thread of the program ends, the threads of other user interfaces are likely to persist to display coherent information, so they cannot be terminated immediately. Here I just give some principles, detailed to the actual application frequently needed
Further careful discussion by programmers. Thread priority Once a thread has started running, the thread-dispensing program can effectively monitor the CPU time it obtains. If a managed application is running on a Windows machine, the thread-dispensing program is provided by Windows. On other platforms, the thread dispensing process may be part of the control system, and it may be natural. Part of the NET Framework. But we don't have to think about how the thread-dispensing program is generated, we just know that by setting the priority of the thread we can make the thread get the difference in CPU time. The priority of a thread is effectively supervised by the Thread.priority attribute, and its value implies: Threadpriority.highest, Threadpriority.abovenormal, Threadpriority.normal, Threadpriority.belownormal and Threadpriority.lowest. From their names we can naturally know their priority, so there is no more introduction. The default priority for a thread is threadpriority.normal. In theory, a thread with the same priority gets the same CPU time, but in practice, the thread in the message line or the precedence of the system will cause the thread with the same priority to get the difference in CPU time. However, the overall consideration can still ignore this difference. You can change the priority of a thread in the following ways. Thread. Priority=threadpriority.abovenormal; or: Thread. Priority=threadpriority.belownormal; You can raise the priority of a thread by using the first sentence above, so the thread will get more CPU time; the second sentence makes you lower the priority of that thread, So it will be allocated less CPU time than the original. You can change the priority of a thread before it starts running or at any point in its operation. In theory you can also arbitrarily set the priority of each thread, but a high priority thread will often affect the operation of other threads, or even edification to other programs, so it is best not to arbitrarily set the priority of the thread. Suspending a thread and starting from scratch thread class differences provide two ways to suspend a thread and start a new thread, that is, Thread.Suspend can suspend a running thread, and thread.resume can keep that thread running. Unlike the Windows kernel,. NET Framework does not record the number of times a thread hangs, so whenever you suspend a thread repeatedly, just one call to Thread.resume allows the pending thread to start anew. The thread class also provides a static Thread.Sleep method that enables a thread to automatically suspend a positive time and then automatically start over. A thread can call the Thread.Sleep method inside itself, and it can call the Thread.Suspend method inside itself, but it must be another way to invoke its Thread.Resume method to start anew. This is not very easy to figure out ah? The following example shows how to apply the Thread.Sleep method: while (continuedrawing) {drawnextslide (); Thread.Sleep (5000);} Terminate thread in managed code, you can terminate another thread in one thread by using the following statement: Thread. Abort (), let's explain how the Abort () approach works. Because the common language runtime governs a fully managed thread, it can also throw exceptions within each thread. The Abort () method throws a ThreadAbortException exception in the directional thread, causing the end of the directional thread. However, after the abort () method is invoked, the directional thread may not terminate immediately. Because as long as the direction thread is calling unmanaged code and has not returned, the thread will not terminate immediately. If the direction thread calls unmanaged code and falls into a dead loop, the direction thread will basically not terminate. However, this situation is only a few exceptions, more of the situation is the direction of the thread in the call to the managed code, once the Abort () is called then the thread immediately terminated. In practice, one thread terminates another thread, but it is always necessary to wait for the thread to terminate before it can run continuously, so we should use its join () method. The sample code is as follows: Thread. Abort ()//requires terminating another thread threads. Join ()//only to another thread all terminated, and it kept running but if another thread never terminates (as explained earlier), we need to set a time limit for the join () method as follows: Thread. Join (5000); Pause for 5 seconds so that the thread is forced to run after 5 seconds, regardless of whether the thread has terminated. The method also returns a Boolean value, if true, to comment that the thread has been terminated, and if False, the commentary has exceeded the time limit. The clock thread.
NET Framework, the Timer class allows you to take advantage of the clock thread, which is contained in the System.Threading namespace, and its function is to call a thread after a certain interval. Below I show the public a detailed example of a 1-second interval in which the difference is output in a valid supervisor, with the following code: usingsystem;usingsystem.threading;classmyapp{ Privatestaticboolticknext=true;publicstaticvoidmain () {Console.WriteLine ("Pressentertoterminate ..."); Timercallbackcallback=newtimercallback (Ticktock); Timertimer=newtimer (callbacknull10001000); Console.ReadLine ();} Privatestaticvoidticktock (ob Jectstate) {Console.WriteLine (ticknext?) Tick ":" tock "); ticknext=! Ticknext}} From the above code, we know that the first function callback is generated after 1000 milliseconds, and the function callback is then generated every 1000 milliseconds, which is determined by the third parameter in the Timer object's constructor. The program will continue to generate new threads after a 1000-millisecond interval, only until the user enters the carriage return to the end of the run. However, it is worth noting that although we set the interval to 1000 milliseconds, the actual running times are not very accurate. Because Windows control system is not a real-time system, and the common language runtime is not real-time, so because of the vagaries of the thread adjustment, the actual operating results are often not accurate to the millisecond, but for the general application that is enough, so you do not have to be very demanding. Summary This article describes the. NET to carry on the basic knowledge which the multithreaded programming needs to grasp. From the article we can know in the. NET multithreaded programming in the past has been greatly simplified, but its function has not been weakened. Using some of the basics above, readers can try to write. NET of multithreaded programs. But to write out more and more compact and less bug-threaded applications, readers need to grasp such as thread synchronization, thread pool and other high-end multithreaded programming skills. Readers may wish to refer to a number of technical books that govern the system or multithreaded programming.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.