Column
.NET framework and multi-threaded
Yuan Jian
.NET framework and multi-threaded
This article is published in "Program Spring and Autumn" 2003 12
Summary
This article describes the basic concepts of the .NET framework and briefly describes how to use the .NET framework to write multi-threaded programs.
table of Contents
• Overview
• Features
? Programming model
? Thread overview
? Thread control
? Thread synchronization
Overview
Microsoft.net represents a collection, an environment, a programmable structure that can support the next generation of Internet as a platform, which makes each system platform interoperability into a reality, Microsoft.Net is the most important part of using HTTP, XML and other standards. Yes .NET framework, .NET framework is a new computing platform that simplifies applications developed in a highly distributed Internet environment, which supports more than 20 different programming languages, which helps developers concentrate on achieving energy On the core of business logic, developers' experience is consistent in the face of a large type of application (such as Windows-based applications and web-based applications), and even in future versions even in the program In order to specify the type of published (as Win Form or web form).
As shown in the figure above, the .NET framework consists of 2 parts: public language runtime (CLR: is an intermediate medium between the source code of .NET developers, all .NET code runs in CLR) and Frame Class libraries (FCL: Includes data access components, basic class libraries, and WebForm, WinForm, Web Services template).
Features
CLR and FCL are closely combined, providing cross-and integrated solutions and services between different systems, creating controllable, safe, featured application development environments, the following is some of their features they provide.
Once run, can always run
All developers have almost all know the "DLL Hell" version control problem (when the newly installed application component covers the old application's components, the old program cannot run normally). In order to completely eliminate the "DLL Hell" phenomenon, the structure of the .NET framework has been isolated from the application component, the application must be loaded when the application is running to ensure that the application can always operate normally.
Simplified deployment
The software installation in the .NET frame is Xcopy, just as in DOS, you only need to copy the application to a directory to complete the installation, and uninstall the application only needs to delete the directory.
Automatic memory management
For managed resources, you don't have to clean up in the Class Writing Function (FINALIZE), the garbage management (GC) can automatically use the resource usage, make sure that the resource leak will not generate, in fact, GC is not the time and order of Finalize's call time and order. definite. However, Microsoft recommends that users must remember to release unmanaged resources such as database connections, files, and more in the Dispose method.
Type security
Each object is a single inheritance from Object (Note: It is also considered to be inherited from the IObject interface) to ensure that the GetType method can determine the type of object by calling the GetType method, usually forced to convert to the base type is considered a security hidden Conversion. The CLR can verify that all codes are safe, and the type security ensures that the assigned object is always accessed in a compatible manner.
Programming model
Most of the C developers developed under the Windows platform is mostly used by the Microsoft Basic Library (MFC) or Win32 APIS. Visual Basic users use Visual Basic API, Delphi users use Borland's VCL, Java users. JDK, it is difficult to compatibility between each other, call each other, software developers sometimes difficult to pay, and the .NET framework unified the current different architecture, .NET framework provides developers with a unified, object-oriented, level Chemical, scalable framework class library - FCL, developers no longer need to learn a variety of architectures only need to learn .NET frameworks can be flexible to develop a variety of different programming languages, .NET framework also implements cross-language Inheritance, error handling, debugging. All programming languages from C #, VB.NET, J # to C are equally equally in the .NET framework. Developers can freely choose their favorite language, program code of different languages:
C #: Class Hello {static void main () // Export point {System.Console.write ("Hello, World!"); // Output hello, world!}} VB.NET: Module Hello Sub Main () 'The export point of the program System.Console.write ("Hello, World!")' Output Hello, World! End Sub End Module finally generated on the compiler is the following IL (intermediate language) code: IL_0000: LDSTR " Hello, World! "IL_0005: Call void [mscorlib] System.console :: Write (string) IL_000A: RET
IL is the only understanding language of the CLR, all compilers compile the source code into IL, IL is processed by CLR.
The result of the output is very familiar: Hello, World !.
In the .NET framework you can not only develop traditional Windows-based applications, you can also develop applications under Smart Phone, Pocket PC, Tablet PC, and the like.
The .NET framework provides a powerful programming template that can write WinForm, WebForm, WebService such as WinForm, WebForm, WebService, which have great significant differences in the development of these types, and the functions are greatly strengthened than ever. Among them, "the most likely to change the world" (Note: Jeff ProsiSe), the most surprising should be web form (ASP.NET). Multi-Thread, GDI , Design Mode, Cache, Exception, etc. These are not imagined in the previous web program or difficult to implement in the .NET framework.
ASP.NET is almost born based on MVC mode. It uses Code-Behind technology to separate the page (View) and code (Model && Control), plus Page Controller, Distributed, Services, etc., you can use the program structure from Traditional 3-layer expansion to 4 layers, 5 or more layers, fully meet the needs of developing large enterprise applications (will have an opportunity to develop exciting side to develop the ASP.NET combined mode to you later). With multi-threaded and GDI technology, you can display text content while the image is captured and transformed into an appropriate form (such as converted to a PNG format) to the user, the efficiency is greatly improved than ever. For quite a few people, develop multi-thread programs is a considerable challenge, but .NET framework has been aware of a considerable degree of simplification, and the following sections will introduce you to multithreaded programming basics, and provide Some sample code for the test. I believe you will be able to master it after you have seen it.
For ease of explanation, the sample code uses a console program.
Thread outline
Threads are units allocated by CPU, different threads can have different priorities, and each process will have at least one main thread. The most basic execution unit in the .NET frame is a thread, the hosted code is executed in single thread, but can generate additional threads during execution to help complete the specified task. The thread is divided into a front desk (all front desk threads must be exited, the current process can exit) and the background thread (the process can exit at any time, not waiting for the background thread).
For operational time and do not want to block the operation of the interface, the server side should be considered when supporting multiple users, and should consider using multithreading, but using threads need to be very cautiously analyzed. Synchronization And thread scheduling itself overhead.
Thread control
Thread control includes thread start, suspend, recovery, sleep, termination, etc., the thread control will be a general description of thread control in this list below.
Public class mythread {public static void Work () {try {for (int i = 0; i <4; i ) {console.writeline (thread.currentthread.name "is calculated" i.tostring ()); thread .Sleep (50);}} catch (threadabortexception e) {console.writeline ("Error message: {0}", E.MESSAGE); thread.resetabort (); // Cancel the request for the main thread requirements, if not Execute ThreadAbortexception once again raised} console.writeline (thread.currentthread.name ");}}}}}}}}}}}}}}}}}} Class threadAbortTest {public static void main () {Console.WriteLine (" Main thread start! " "Thread thread = new thread (new threadstart (mythread.work)); // mythread.work Represents the thread function to be executed, it can be static, or a method of a class instance, it is to be executed Thread.Name = "mythread"; thread.start (); thread.start (); // The thread will be scheduled by the CPU, but it is not necessarily implemented immediately, so the same example may have different results on different machines. . Console.writeline ("The main thread sleeps for the first time!"); Thread.sleep (100); console.writeline ("Mythread is hang!"); Thread.suspend (); // hangs the sub-thread console.writeline "The main thread is the second time!"); Thread.sleep (100); console.writeline ("Mythread is restored!"); Thread.Resume (); // Recovery sub-thread.abort (); // terminate Sub-thread thread.join (); // until the sub-thread is completely terminated, the main thread will continue to run console.writeline ("Main thread termination!"); Console.readline ();}} The program will create a name after startup To the auxiliary thread of Mythread and start it by calling thread.start, then call thread.sleep (100) to sleep 100 subtle, then the auxiliary thread has been running, then the main thread calls thread.suspend hangs the auxiliary thread and sleeps 100 After subtle, call the Thread.sleep to restore the secondary thread, and the secondary thread is blocked during the suspend and recovered, follow the main thread to perform the thread.abort method to terminate the auxiliary thread and perform thread.join Wait auxiliary thread end, When the auxiliary thread receives the termination request, it has worked and executed a loop, and the auxiliary thread captures the exception of the main thread, and executes Thread.Resetabort exits the loop to perform cleanup work. From the above example, you can clearly see the entire process of controlling concurrent threads. The results of the operation are shown in Figure 2:
Thread synchronization
The starting thread is easy, but it is difficult for them to coordinate the work, the most difficult thing to design a multi-thread is to calculate the constructed thread where conflicts and synchronous logic to prevent conflicts.
The .NET framework provides several thread synchronization classes:
? AutoreteTevent: Blocking thread until another thread setting event
• Interlocked: Simple operation in a thread safe, such as incrementing or decreasing an integer
? ManualRetevent: block one or more threads until another thread set event
? Monitor: Prevent more threads from accessing a resource
? Mutex: Prevent one or more threads from accessing a resource at the same time and can cross the border of the application or process
? ReaderWriterlock: Make multiple threads to read a resource at the same time, but not allow overlapping read and write or write operations
In the above several classes we used up to Monitor, the following will focus on the Monitor class:
Several important methods of Monitor:
• Enter: Calling before accessing resources and declares a lock on the resource to determine if the resource is occupied by other resources, if the thread is blocked until the resource can be obtained.
• EXIT: Turn on the resource to release the resource to access other threads after visiting the resource.
? Wait: Temporarily abandon the lock of the call thread to the resource.
Pluse: Informs the thread to block in Wait, so that the next wait thread can run after the current thread releases the lock.
There is a lock key in C # to replace Monitor's Enter and Exit, in function
Lock (someresource) {// your processing code} is equivalent to: Monitor.Enter (Someresource); try {// your processing code} finally {monitor.exit ()
The following example shows you how to use Monitor to achieve producers - consumers. On the surface, only one method can be executed at each time, but they are executed concurrent. The first is that producer gets the lock. He passes the Monitor.Wait to block itself, then consumer gets the lock, consumer calls Monitor.pulse makes the producter in the preparation status, then consumer calls Monitor.Wait block itself, then PRODUCER Call from Wait Wake up, generate a resource into the queue, call Monitor.pulse to wake up from WAIT calls, consumer gets resources from the queue, followed by calling Monitor.pulse and Monitor.Wait makes the entire process continues.
Class Monitorsample {Private Queue_Queue = new queue (); public void product () {int counter = 0; Lock (_QUEUE) // Determine if the resource is occupied by other threads {While (counter <2) {Monitor.wait (_Queue ); // temporarily abandon the lock of the call to the resource, let the consumer execute _queue.enqueue (counter); // generate a resource console.writeline (String.Format ("Production: {0}", Counter); Monitor.pulse (_QUEUE); // Notification in Wait is blocked in Wait will soon perform counter ;}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} {Monitor.pulse (_QUEUE) {Monitor.pulse (_QUEUE); // Notification in Wait blocking Producter thread is about to execute while (Monitor.Wait (10)) {int counter = (int) _Queue.dequeue (); // Remove a resource console.writeline (String.Format ("Consumption: {0}", Counter )))); Monitor.pulse; // Notification in Wait is notified of the PRODUCER thread will be executed}}} static void main (String [] args) {Monitorsample Monitor = new monitorsample (); thread product = new thread (New ThreadStart (Monitor.Producer); thread consumer = new thread (New ThreadStart (); setucer.start (); consumer.Start (); consumer.join (); consule.join (); console.readline ();}}
This article only shows the Icebergs of the .NET framework, which specifically explains the necessary knowledge of developing multi-thread programs under the .NET framework, and should also think that the multithreaded program is .NET when you are familiar with The most interesting and useful thing in the frame.
Reference resource
Microsoft Developer Network
http://msdn.microsoft.com
Microsoft .NET programming technology insider Jeff Prosise, Wang Tie and other translation, Tsinghua University Press
Yuan Jian
Microsoft ASP.NET MVP
http://blog.joycode.com/goodidea
November 2, 2003