Multi-thread in C # ----- Head: http:www.daima.com.cninfo234.htm

xiaoxiao2021-03-06  69

I. Multi-threaded concept   Windows is a multi-task system, if you are using Windows 2000 and above, you can view programs and processes running the current system through Task Manager. What is a process? When a program starts running, it is a process, the process refers to the memory and system resources used by the program and the program in the run. And a process is composed of multiple threads, threads are a execution stream in the program, each thread has its own proprietary register (stack pointer, program counter, etc.), but the code area is shared, that is, different The thread can perform the same function. Multithreading means that multiple execution streams are included in the program, that is, the individual tasks can be done in one program to perform different tasks in a program, which means that a single program is allowed to create multiple parallel execution threads The browser is a good multi-threaded example. In the browser you can scroll the page while downloading the Java applet or image, play movies and sounds, print files, etc. when accessing the new page while accessing the new page. Multi-threaded benefits can improve the Usage of CPUs - any programmer does not want his own procedure to be dry. In multi-threaded programs, a thread must wait, CPU can run other threads Instead of waiting, this greatly improves the efficiency of the program. However, we must also realize that threads themselves may affect system performance, in order to use thread: thread is also a program, so threads need to take up memory, the more threads, the more memory, more threads need to coordinate and manage, so need The CPU Time Tracking Thread Threads will interact to each other, and there is a need to solve the problem threads that can be solved too much. It will cause control too complicated. understanding. Suppose there is a company, there are many staff members in the company, then we can think that the company is a process, and the staff of the company is thread. A company has to have a staff member, which is the same, and a process contains at least one thread. In the company, you can do everything in a staff, but efficiency is obviously high, a person's company is impossible to do it; a program can only use a thread to do things, in fact, some time The language is like Fortune, Basic is the same, but like a person's company, the efficiency is low, if you do a big program, the efficiency is lower - in fact there is now no single-threaded commercial software. The more the company's staff, the more the boss gives them, but also pays a lot of energy to manage them, coordinate the contradictions and interests between them; the procedure is the same, the more resources, the more resources, the needs The CPU time goes to track the thread, but also solves problems such as dead locks, synchronization. In short, if you don't want your company being called "leather bag company", you have several employees; if you don't want your program to be young, introduce multi-thread in your program! This article will explore the multi-thread mechanism in C # programming, solve problems such as thread control, multi-line inter-block communication through some instances. In order to save the cumbersome steps of the GUI, more clearly approximate the nature of the thread, all the procedures below are console programs, the last console.readline () is to stop the program to see the process of implementation Output.

  well, nonsense, let us experience the multi-thread C #! II. Manipulating a thread. Any program is executed, at least one main thread, the following small program can give the reader an intuitive impression: [Code] //systemthread.cs Using System; use system.threading; Namespace Threadtest {class RunIt {[STAThread] static void Main (string [] args) {Thread.CurrentThread.Name = "System thread"; // current thread to named "System thread" Console.WriteLine (Thread.CurrentThread.Name " 'Status: " thread.currentthread.threadstate; console.readline ();}}} [/ code] What did you see after compiling? Yes, the program will produce the following output: System Thread's Status: Running  Here we CurrentThread get the currently executing thread by Thread class static properties, its Name property assignment "System Thread", and finally output Its current state (ThreadState). The so-called static properties are all the properties of this class all objects, whether you have created how many such classes of this class, but the static properties of the class have only one in memory. It is easy to understand why CurrentThread is static - although there are multiple threads exist at the same time, but at a moment, the CPU can only perform one. Just like the above program, we create and control threads through the Thread class. He noted the head of the program, we use the following namespaces: The following is the program code: using System; using System.Threading;  in .net framework class library, all associated with the multithread applications The class is placed in the system.threaming namespace. The Thread class is provided for creating threads, threadpool classes for managing thread pools, etc., and there is also a mechanism to solve the actual problems such as thread implementation arrangements, deadlocks, and thread communication. If you want to use multithreading in your application, you must include this class. There are several vital methods that are critical, describing the following: start (): Start the thread sleep (int): static method, suspend the number of milliseconds specified by the current thread (): usually use this method to terminate a thread supend () : This method does not terminate unfinished threads, which only hangs the thread, and can be recovered later. Resume (): Restore the execution of the thread hangs hangs under the Suspend () method. Let's create a thread. When you create a thread using the Thread class, you only need to provide a thread entry. The thread entry makes the program let this thread do something, in C #, the thread entry is provided through the ThreadStart Agent (DELEGATE), you can understand the ThreadStart as a function pointer, pointing to the thread to be executed, when calling Thread. After the start () method, the thread began executing the function indicated by ThreadStart or points.

Open your vs.net, create a console application, the following code will make you feel the endless pleasure of controlling a thread! // threadtest.cs                                                                                                                                                  Alpha.beta is running in its}}}; public class simple}; public class simple}; "Thread Start / Stop / Join Sample"; alpha oalpha = new alpha () // Create a thread here to execute the Beta () method of the Alpha class () method thread osread = new thread (new threadstart (oalpha.beta)); orthhot.start (); while (! Ketread.isalive); heread .Sleep (1); osread.abort (); osread.join (); console.writeline (); console.writeline ("alpha.beta Has finished"); try {console.writeline ("Try to restart the alpha) Beta thread ");} catch (threadStateException) {Console.Write (" ThreadStateException Trying To restart alpha.beta. ");" Expected Since Aborted. "); console.readline ();} return 0;}}} This program contains two classes Alpha and Simple When you create a thread OTHREAD, we use the initialization of the ThreadStart Agent (DELEGATE) object to the alpha.beta () method. When we created the thread oscart () method, actually run alpha.beta () Method:                                                                          Static method thread.sleep () Let the main thread stop 1ms,

This time the CPU turns to execute thread othread. Then we tried to terminate the thread osread.Join (), the thread.join () method for the main thread until the main thread is over. You can specify an INT type parameter as the longest time waiting for the thread.join () method. After that, we tried to restart the thread oscart () method, but obviously the consequences of the Abort () method are unrecoverable termination threads, so the last program will throw the ThreadStateException. Here we have to note that other threads are attached to the thread of the main () function, the main () function is the entry of the C # program, the starting thread can be called the main thread, if all the front desk threads stopped Then, the main thread can be terminated, and all the background threads will be terminated unconditionally. Although all threads are executed in micro, you can do it in a macro, you can do it in parallel. Readers must notice this attribute of Thread.ThreadState. This property represents a thread run state, there is a different value in different situations, so we can sometimes design the program process by judging the value. ThreadState may take the following values ​​as follows: Aborted: The thread.abort () method of the thread has been called, but the thread has not stopped background: thread executes in the background, with attribute thread.isbackground For Running : The thread is running normally: thread has been stopped STOPREQUESTED: The thread is being required to stop Suspendeded: thread has been suspended (this state, can be re-run by calling the resume () method) SuspendRequested: thread is being required to be hanging, but Future and response UnStarted: Unmarkable thread.start () Start the thread running WaitSleepjoin: Threads Because Wait (), SLEEP () or JOIN () is called in a blockade state, the Background status indicates that the thread is in the background. Run, what is the special place for threads running in the background? In fact, the background thread has only one difference with the front desk thread, that is, the background thread does not hinder the termination of the program. Once all the front desk threads are terminated, the CLR (Universal Language Run Environment) will completely terminate the process by calling the Abort () method of any background process in any survival. When the thread competes for the CPU time, the CPU is served in accordance with the priority of the thread. In the C # application, users can set up five different priorities, from high to low, respect, ABOVENORMAL, NORMAL, BELOWNORMAL, LOWEST, if they do not specify priority when creating a thread, then the system is threadpriority.normal . Give a thread to specify a priority, we can use the following code:                                                                                                                                  设           Thread priority execution, such as response to the user, etc. Now we have a preliminary understanding of how to create and control a thread. Below we will in depth, in depth, the thread implementation is more typical, and explore its solution.

III. Synchronization and communication of threads - Producer and consumers assume that two threads maintain a queue while adding elements to the queue, while another thread takes the elements from the queue, Then we call the thread of the adding elements for the producer, weigh the thread of the element to consumers. Producers and consumers look simple, but it is a problem that must be solved in multi-threaded applications, which involves synchronization and communication issues between threads.   previously said, each thread has its own resources, but the code area is shared, ie each thread can perform the same function. However, in multi-threaded environments, problems that may bring are a few threads simultaneously execute a function, resulting in confusion of data, resulting in unpredictable results, so we must avoid this happening. C # provides a keyword Lock that defines a code as a critical section, and the mutual exclusion section only allows a thread to enter execution, while other threads must wait. In C #, the keyword Lock is defined as follows:                                                          Generally, if you want to protect an instance of a class, you can use this; if you want to protect a static variable (such as the mutually exclusive code segment in a static method), you can usually use the class name. STATEMENT_BLOCK is the code of the mutual exclusion, which is only performed by one thread in one moment.

Below is a typical example of using the lock keyword, I will explain to you to the Lock keyword usage and use: // Lock.cs                                                                                                                                         b                                                                                                                                            less than 0 thrown throw new exception ( "Negative Balance"); }  // the following code modified balance values ​​to ensure that the current thread Before completing, there will be no other threads to perform this code to modify the value of Balance // Therefore, the value of Balance is impossible to less than 0. {THISOSOLE.WRITELINE ("Current Thread:" thread.currentthread.name); // If there is no Lock key The protection of the word, then it is possible to perform Balance = Balance-Amount to modify Balance = Balance-Amount to modify Balance = Balance-Amount.                       This modification is invisible to this thread, so it may cause the conditions of IF that IF has not been established. However, this thread continues to execute Balance = Balance-Amount, so that Balance may be less than                                                                                                                                                                                                                                                                                  Return 0; // ITERNAL VOID Dotransactions ()                                                                                                                      i <100; i ) Withdraw (r.Next (-50, 100)); } } internal class Test  {static internal Thread [] threads = new Thread [10]; public static void Main ()  {Account acc = new Account (0); for (int i = 0; i <10; i )  {Thread t = new Thread (new ThreadStart (acc.DoTransactions)); threads [i ] = t; } for (int i = 0; i <10; i ) threads [i] .Name = i.ToString ()   prov - I = 0; i <10;

转载请注明原文地址:https://www.9cbs.com/read-87981.html

New Post(0)