The second chapter of the ". NET programming Pioneer C #" Theoretical Foundation-Common Language Runtime environment (turn)

Source: Internet
Author: User
Tags abstract exception handling execution garbage collection object model stub valid versions
Programming chapter II Theory Foundation-common language running environment
Now that you have a complete impression of C #, I want you to know the full picture of NGWS runtime. C # relies on the runtime provided by NGWS, so it is necessary to know how the runtime works and the concepts behind it.
So, this chapter is divided into two parts--they are all concepts and the basis of use. Although there is some overlap in the content of the two parts, it helps to deepen the understanding of the concepts under study.

2.1 Ngws Runtime
NGWS and NGWS runtime provide you with a run-time environment. The runtime manages the execution of code and provides services that make programming easier. As long as your compiler supports this kind of operation, you will benefit from this managed execution environment.
You suspect that the C # compiler supports NGWS runtime is correct, but not only does it support NGWS Runtime,vb and C + +. The code that is created to support the runtime is called "Managed Code" (managed). The following are the benefits of your application from NGWS Runtime:

Cross-language integration (through the common Language specification)
Automatic memory management (garbage collection)
Cross language exception handling (Unified expansion)
Enhanced security (including type safety)
Version Support (DLL Hell Terminator)
Component Interaction Simplified Mode

Because NGWS runtime to provide all of these benefits, the compiler must send the meta file and the managed code together. The meta file describes the type in the code, and it exists with your code (like PE---PE is a variable bit executable file)
As you can see from many of the cross language features, NGWS runtime is primarily about highly integrated, cross-heterogeneous programming languages (tight integration across multiple different programming). This support can be achieved by allowing you to derive a C # class from a VB object (I'll give you an article to discuss later).
One feature that C # programmers will like is that they don't have to worry about memory management-that is, not having to worry about notorious memory leaks. NGWS Runtime provides memory management that the garbage collector releases when the lifetime of objects and variables ends (no longer referenced). I really like this feature, because memory management in COM is always a piece of my heart.
You should encourage the configuration of a management application or component. Because the management application contains metadata files, NGWS runtime can take advantage of this information to ensure that your application has the various prescribed versions that it needs. The obvious effect is that because your code does not depend on each other, there is little likelihood of interruption.
The remainder of this chapter will be divided into two parts, each of which discusses all aspects of NGWS runtime until your C # application can execute.
1, intermediate language (intermediate Language, abbreviation IL) and metadata
2, Instant compiler (Just-in-time compliers, abbreviation jiters)

2.1.1 Intermediate language and meta data
The managed code generated by the C # compiler is not the original code, but it is an intermediate language (IL) code. This IL code itself becomes the gateway to the managed execution process of the NGWS runtime. The obvious advantage of IL code is that it is CPU-independent, which means that you have to use a compiler on the target machine to convert the IL code to the original code.
Although the IL code is generated by the compiler, it is not what the compiler provides to the runtime. The compiler also generates metadata about your code, which tells the runtime more about your code, such as various types of definitions, signatures of various types of members, and other data. Basically, the metadata is the type library, the registry content, and other information used for COM. Still, the metadata is merged directly with the execution code, not in an isolated location.
Il and metadata are stored in files that extend the PE format (the PE format is used for. exe and. dll files). When such a PE file is loaded, the runtime locates and detaches the metadata and IL from the file.
Before I explain further, I'd like to give you a short list of existing IL directives. Although it is not a complete list, it does not require you to memorize and understand it, but it lists the knowledge bases that you need to base the C # program on.

Arithmetic and logical operators
Control flow
Direct Memory Access
Stack operation
Parameters and Local Variables
Stack allocation
Object mode
Instance Type value
Critical Zone
Array
Type position
Just-in-time Compiler (JITTERS)

2.1.2 Instant compiler (jitters)
The managed code generated by C # or other compilers capable of producing the managed code is the IL code. Although the IL code is wrapped in a valid PE file, you cannot execute it unless it is converted into a managed source code. This is when NGWS runtime instant compilers (also known as jitters) are doing their thing.
Why do you get tired of Just-in-time compiling code, and why not compile the entire IL pe file into the original code? The answer is time--the time required to compile the IL code into CPU-spec code. This compilation will be more efficient because some of the program segments have never been executed. For example, in my word processor, the mail merge feature has never been compiled.
Technically, the whole process is as follows: When a type is loaded, the loader creates a stub and makes it connect to each type of method. When a method is invoked for the first time, the stub hands control to the JIT. The JIT compiles the IL into the original code and points the stub pointer to the buffered raw code. The next call executes the original code. In some locations (at some point), all IL is converted to the original code, while the jitter is in an idle state.
As I mentioned earlier, there are a number of JIT compilers, more than one. On the Windows platform, the NGWS runtime contains 3 different JIT compilers.
jit--This is the JIT compiler used by the NGWS runtime default. It is a backend-optimized compiler that implements data flow analysis in the foreground (up front) and creates highly optimized managed raw code as output results. The JIT can be encoded with an less stringent IL instruction set, but the required resources will be significant. The main limitations are memory footprint (footprint), result working sets, and the time it takes to implement optimizations.
econojit--and Master JIT, the goal of Econjit is to convert IL into managed raw code at high speed. It allows buffering of the raw code generated, but the output code is not as optimized as the master JIT-generated code (small code). When memory is tight, the advantages of a quick code generation scenario are gone. By permanently discarding useless, JIT-enabled code, you can load a larger IL program into the code buffer. Because JIT compilation is fast, execution speed is still very fast.
prejit-Although it is based on the master JIT, it operates more like a traditional compiler. You install the NGWS component before it can be run to compile the IL code into the managed raw code. The end result, of course, is faster load times and faster application startup times (no more JIT compilation).
Of the listed jitters, there are two jitters at run time. But how do you decide which JIT to use, and how does it use memory? There is a small application (Jitman.exe) called the JIT compilation manager, which is stored in the bin directory under the NGWS SDK installation directory. When you execute the program, it adds an icon to the System task bar and double-clicks the icon to open the Program dialog box (see Figure 2.1).

Figure 2.1 JIT compilation Manager allows you to set options for various related performance

Although it is a small dialog box, the options you choose are quite powerful. Each option is described in the following.
Use Econojit the only option-when the check box is not selected, NGWS runtime uses the default normal JIT compiler. The difference between two kinds of jitter has been explained before.
Max Code Pitch overhead (%) option-This setting is reserved for Econojit only. It controls the percentage of JIT compilation time and execution code time. If you exceed the set domain value, the code buffer is expanded to shorten the time that JIT compilation consumes.
Limit Size of Code cache option-This is not selected by default. Not selecting this item means that the buffer will use the memory it can get. If you want to limit the buffer size, check this option, which will allow you to use the Max Size of Cache (bytes) option.
Max Size of Cache (bytes) option-controls the maximum value of the buffer that holds the JIT code. Although you can limit this value very strictly, you should be careful not to exceed the maximum value that the buffer fits. Otherwise, the JIT compilation of the method will fail.
Optimize for size option-tells the JIT compiler that the purpose of the optimization is to make the code smaller rather than faster. This setting is turned off by default.
The Enable Concurrent gc[garbage Collection] option-garbage collection (GC) runs by default in the thread of user code. This means that when a GC occurs, it may be noted that there is a slight delay in response. To prevent this behavior from occurring, open the current GC. Note that the current GC is slower than the standard GC, and it is only valid when written on Windows 2000 (the time of writing).
When you create a project in C #, you may have experimented with different settings. When you create a ui-intensive application, you will see the maximum difference that allows the current GC.

2.2 Virtual Object System (VOS)
So far, you've only seen how NGWS runtime works, but doesn't know the technical background of its work and why it works like this. This section is all about the NGWS virtual object System (VOS).
The following are the rules for NGWS runtime when declaring, using, and managing type models in Vos. The idea behind Vos is to build a framework that does not sacrifice performance when executing code, allowing for cross language integration and type safety.
The framework I mentioned is the foundation of the Run-time architecture. To help you better understand it, I'll hook it up to four areas. When developing C # applications and components, it is important to understand them.
Vos type System-provides a rich type system that is intended to support full implementation of a comprehensive programming language.
Metadata--describes and references the types defined by the Vos type system. The permanent format of the metadata is independent of the programming language, but the metadata is used as an interchange mechanism (Nterchange mechanism) between the tool and the NGWS virtual execution system.
The common Language Specification (CLS)--CLS defines a subset of the types in Vos and also defines general usage. If a class library adheres to CLS rules, it ensures that class libraries can be used on all other programming languages that can implement the CLS.
Virtual Execution System (VES)--This is a real-time implementation of VOS. The VES is responsible for loading and executing the procedures prepared for the NGWS.
These four sections together form the NGWS runtime architecture. Each section is described in the following section.

2.2.1 Vos type System
The Vos type system provides a rich type system that is intended to support the full implementation of multiple programming languages. Therefore, Vos must support object-oriented language and process programming languages.
Now, there are many kinds of approximate but somewhat incompatible types. Take the integral type as an example, in VB, it is 16 bits long, and in C + +, it is 32 bits. There are more examples, especially for data types that are used in dates and times and databases. This incompatibility makes the creation and maintenance of an application unnecessarily complicated, especially when a program uses multiple programming languages.
Another problem is that because there are some differences between programming languages, you cannot reuse the type created by another language in one language. (COM partially solves the problem with the binary standard interface). Today's code reuse is certainly limited.
The biggest hurdle to publishing an application is that the object model for various programming languages is not uniform. There are differences in almost every aspect: events, attributes, Permanent saves (persistence), and so on.
Vos here will change this phenomenon. Vos defines the type that describes the value and sets a contract that must be supported for all values of the type. With the aforementioned support for object-oriented and procedural programming languages, there are two of values and objects.

For a value, the type is stored in the presentation (representation), and the same operation is implemented in it. Object is more powerful because it is explicitly stored in the statement. Each object has an identification number that distinguishes it from other objects. Support for different Vos types is presented in the fourth chapter, "C # types."


2.2.2 Meta data
Although metadata is used to describe and reference types defined by the Vos type system, it cannot be locked to this single target. When you write a program, by using type declarations, the types you declare (assuming they are numeric types or reference types) are introduced to the NGWS runtime type System. The type declaration is described in metadata that is stored inside the PE executable file.
Basically, metadata is used for tasks: information that is used to represent the purpose of NGWS runtime, such as locating and loading classes, cases of these classes in memory, resolving calls, translating IL to Raw code, enforcing security, and setting runtime context boundaries.
You don't have to care about the generation of meta data. The metadata is generated by the C # code-IL compiler (Code-to-il compiler, not the JIT compiler). The code to IL compiler sends binary metadata information to the PE file, which is sent in a standard way and does not create their own decorated names for export functions like C + + compilers.
The main advantage you get from the coexistence of metadata and executable code is that the information about the type is fixed with the type itself, not in many places. It also helps resolve version issues that exist in COM. Further, you can use different versions of the library in the same context, because the library is referenced not only by the registry, but also by the metadata references in the executable code.


2.2.3 General Language Specification
The common Language Specification (CLS) is not a real part of the Virtual object System (VOS), it is special. The CLS defines a subset of the types in Vos and also defines the general usage that must be CLS-compliant.
So what's so confusing about that? If a class library adheres to CLS rules, and other programming languages also adhere to CLS rules, the class library can also be used by customers in other programming languages. The CLS is about the interactive operability of language (interoperability). Therefore, the general usage must follow only externally accessible items (externally visible items) such as methods, properties, events, and so on.
The advantage I have described is that you can do the following work. Write a component in C #, derive it in VB, because the function that add in VB is so powerful, in C # again derive it from VB class. This is possible as long as all external accessible items comply with the CLS rules.
The code I present in this book does not care about CLS agreements. But be aware of CLS agreements when building your class library. I provide table 2.1, which defines the contract rules for types and external accessibility items.
This list is not complete. It contains only a few important items. I do not point out each type of CLS agreement that appears in this book, so it is a good idea: when you look for a CLS contract, you should at least browse the table to see which functionality is valid. Do not worry that you are unfamiliar with each of the meanings in this chapter, and you will learn them in this book.

Table 2.1 Types and functions in the language specification

bool
Char
Byte
Short
Int
Long
Float
Double
String
Object (mother of all objects)

Arrays (Array)
The dimension of the array must be known (>=1), and the minimum subscript must be 0.
The element type must be a CLS type.

Type (Types)
can be abstracted or hidden.
0 or more interfaces can be implemented. Different interfaces allow methods with the same name and signature.
A type can be accurately derived from a type. Allow members to be overwritten and hidden.
You can have 0 or more members, which are fields (fields), methods, events, or types.
A type can have 0 or more constructors.
The accessibility of a type can be public or local to the NGWS component, but only public members can be considered part of the type interface.
All value types must inherit from the system value type. An exception is an enumeration--it must inherit from the System enum (Systems enum).

Type Members
Type members allow you to hide or overwrite other members of another type.
Both the parameter and the type of the return value must be CLS contract types.
constructors, methods, and properties can be overloaded.
A type can have abstract members, but only if the type is not encapsulated.

Method
One method can be static, virtual, or instance.
Virtual and instance methods can be abstract or an implementation. A static method must always have an implementation.
The virtual method may be the last (or not).

Field (Fields)
can be static or non-static.
Static fields can be described or initialized only.

Property
Properties can be exposed when fetching and setting methods instead of using property syntax.
The return type obtained and the first parameter of the set method must be of the same CLS type--the type of the property.
Attribute names must be different, and different attribute types are not sufficient to differentiate.
Because using methods to implement property access, if PropertyName is a property defined in the same class, you cannot implement a method named Get_propertyname and Set_propertyname.
Properties can be indexed.
Attribute access must follow this naming format: Get_proname,set_propname.

Enumeration (enumerations)
The accent type must be byte, short, int, or long.
Each member is a static description field of an enumeration type.
An enumeration cannot implement any interface.
You are allowed to set the same value for multiple fields.
An enumeration must inherit the system enumeration (implied in C #)

Abnormal
Can be raised and captured.
Custom exceptions must inherit system exceptions.

Interface
You may need to implement additional interfaces.
An interface can define properties, events, and virtual methods. The implementation depends on the derived class.

Event
The addition and cancellation methods must be either supplied or not, each method takes a single parameter, and it is a class derived from the system Delegate.

Custom properties
You can use only the following: type (type), char, char, BOOL, BYTE, short, int, long, float, double, enum (a CLS type), and object.

Representative Yuan (delegates)
can be created and activated

Identifiers (Identifiers)
The first letter of an identifier must come from a restricted set.
By capitalization in a single range, it is not possible to have two or more identifiers (not case sensitive) for unique regions.

2.2.4 Virtual Execution System (VES)
Virtual execution system realizes the virtual object system. Create the VES by implementing an executive engine (execution engine, abbreviated EE) responsible for NGWS runtime. This execution engine executes the application that you write and compile in C #.
The following components are part of the VES.
1, intermediate language (IL)--is designed to be easily compatible with a variety of compilers. Outside of the framework, the C + +, VB, and C # compilers can generate IL.
2. Load the managed code-this includes resolving the memory name, surface class (laying out classes), and creating the stub necessary for JIT compilation. The class loader also enhances security by performing regular checksums, including enforcing some access rules.
3, with the JIT conversion Il into the original Code--il code is not designed to become a traditional interpretation of byte code or tree code, IL Conversion is true compilation.
4. Loading metadata, verifying type safety and completeness of method
5, garbage collection (GC) and exception handling-both are based on stack format services. The managed code allows you to dynamically track the stack. To dynamically identify each stack frame, the jitter or other compiler must provide a code manager.
6, mapping and error-checking services-both depend on the information generated by the source language compiler. Two mappings must be issued: A map sent from the source language structure to the address in the instruction stream, and a mapping from the address to the location in the stack frame. These mappings are recalculated when the conversion from IL to the original code is performed.
7, manage threads and contexts, and remote administration--ves provide these services for managed code.
Although this list is not complete, it is sufficient to allow you to understand the low-level architecture provided by the VES at runtime. There is certainly going to be a book devoted to the runtime, and the book will delve into a variety of topics.

2.3 Summary
This chapter, I take you to stroll around the world at the time of the run. I described how it works when you create, compile, and configure a C # program. You learn the intermediate language (IL), and how the metadata is used to describe the type that is compiled to IL. Both metadata and IL are used for jitter detection and execution of your code. You can even choose which jitter to use to execute the application.
In the second part of the chapter, the theory of why the runtime works in this way is covered. You learned the Virtual object System (VOS) and the part that made it. The common Language Specification (CLS) is the most interesting for class library designers, and it sets rules for VOS-based language interoperability. Finally, you see how the Virtual Execution System (VES) implements Vos through NGWS runtime.


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.