Lecture 6th: How to Use. NET to develop Windows Applications

Source: Internet
Author: User

2004.12.21 ou yanliang

Course Introduction

Go deep into Microsoft. NET Framework

 

Basic Content

Familiar with. NET

 

Course Content

Managed Execution)

Assembly (Assemblies)

Namespaces)

Delegate)

Thread

Application domain (AppDomains)

Framework class

Attribute in the program)

Data Type

Reflection (Reflection)

Framework programming

 

Managed execution

Managed code and unmanaged code

The managed code is the code that is compiled for the first time after the intermediate code is formed. When it is executed, it needs to be compiled for the second time. It is not a local code on a computer, but an intermediate form of code.

The essential difference between managed code and unmanaged code: one is intermediate code, and the other is local machine language.

Common Language Runtime (CLR)

When the hosted code is compiled by the compiler for the first time, some classes are provided when the application is loaded. After the program in the managed code is loaded into the memory, it will compile the managed code into local code in real time through JIT and then execute it.

Intermediate Language (IL)

The application Assembly formed after the first compilation by the compiler should be managed code expressed in an intermediate language. during actual execution, the CLR will load the managed code into the memory and perform real-time compilation. This managed code is actually consistent across multiple platforms, but during actual running, it will be compiled in real time based on some code features on the current platform to form local code.

ILDASM

This tool can be used to decompile managed code.

Public System

Ensures multi-language interoperability.

Memory Management

Non-deterministic memory collection: when we set the pointer to null, the pointer is not released because of the garbage collection mechanism.

Garbage Collection: periodically recycles memory space that is not pointed to by pointers.

IDispose: It gives developers a certain opportunity To Recycle resources consumed in unmanaged code. The memory of managed resources is automatically recycled by garbage collection, but the unmanaged objects referenced in the managed code are not recycled, such as file handles, when we want to use a file handle, we must implement the IDispose interface to actively Recycle resources.

 

Managed Code Execution Process

The code is compiled for the first time to form the managed code of the IL intermediate language. After being loaded by Class Loader during runtime, JIT is compiled for the second time to form the hosted local code. During the execution process, it constantly checks the security and standardization of the Code currently executed.

When Class Loader loads the executable program exe or dynamic link library dll, it does not load all the Class libraries in the exe and dll into the memory. It is the first part of the load, that is, the file where the Main function is located, then, during the execution process, Class Loader constantly checks whether the method to be called in the current execution process has been loaded into the memory. If not, it loads some unloaded code in real time. After it is loaded in, it is compiled into a hosted local code and then called.

 

Common Language Runtime (CLR)

Thread support

Type check

Security Engine

Locally compile MSIL

Code Manager

Garbage Collection

Class Loader

COM extends aller: interoperation of COM components

Exception management

Debugger

 

Public System

A framework is created to help implement interoperability, type security, and high-performance code execution between different languages.

Provides a unified object-oriented model that fully supports all languages

A set of language specifications defined to help interaction between different languages

 

Assembly (Assemblies)

An assembly is a set of types and resources, which together form certain logical functions.

Contains a list of types or programs (manifest), type original data, MSIL, resources

The Assembly List describes the types in the application assembly and where these programs are stored. It specifies where my code is located, where it may be on a disk, and where other resources may be on the Internet. Manifest is eventually used by Class Loader. When Class Loader dynamically loads a Class library, it needs to know where the Class library is located and which file. When writing an application, we can describe the location of the Assembly in the Assembly list as an Http address on the Internet, when Class Loader loads this Class in real time, it loads the Library on the remote server from the Http path, which implements zero deployment, we do not need to force the client to update the Dll after it is updated.

All units that can be deployed are compiled MSIL (executable intermediate code)

Lightweight executable file (PE file) EXE or DLL

When the. NET Framework Program is executed, it has a public-type system, and the implementation of these public-type systems is in CLR. When running a program, we use a large number of class libraries defined in the Framework, and the client has actually installed the Framework when executing the application, that is to say, it has helped us deploy many existing functions on the client. After our program is completed, many class libraries do not need to be packaged in our execution file. We only need to put the execution file to the client to call the class libraries in the client Framework. In this way, the number of applications we write is small, but the memory usage is large.

You can use ILDASM and Reflection to check the Assembly

It can be a single file or multiple files

 

Namespace

A namespace is a named container.

Namespaces can organize classes in a hierarchical manner.

Avoid Name Conflict

Usage of the help prompt class

Namespaces can span projects/assembly

Recommended: CompanyName. Project <. Module>. Class

Example: Northwind. OrderEntry. Order

 

Demonstration 1

Assembly and namespace

 

Delegates

Delegate is actually a class in. NET and is a strongly typed function pointer.

Mainly used for event processing and callback

Multicast Delegate: The Combine and Remove methods can be used to add or Remove the call list in Delegates.

You can use Invoke to call the method pointed to by Delegate.

You can use Delegate to complete asynchronous calls. The BeginInvoke and EndInvoke Methods

The implementation of Delegate is provided at runtime, so you do not need to care about it.

Delegate determines the user code to be called at runtime. You need to write the code

 

Demonstration 2

Delegates

Running result

932 indicates the interface thread ID, and 1380 indicates the thread ID during asynchronous calling. That is to say, BeginInvoke creates a thread for us to execute the function pointed to by our function pointer.

This method has some advantages. The SimpleDelegateHandler method is located inside the MainClass class and can access some private members in the MainClass, but the DelegateExample class cannot be accessed. Therefore, the SimpleDelegateHandler method is passed into the CallMeBack function of the delegat, you can complete the call. That is to say, if you want to update or set Private Members in the MainClass in CallMeBack, we can create a Delegate in the MainClass and make a callback through the CallMeBack in the external DelegateExample class, callback to the SimpleDelegateHandler method, in which private members in MainClass can be accessed.

 

Thread

Multi-task operating system with priority-"time slice" assigns the clock cycle to multiple threads

Multithreading technology allows a worker thread to perform a long time computing and UI operations of corresponding users.

The System. Threading. Thread class actually describes a System Thread.

ThreadPool. QueueUserWorkItem () can be used to perform some operations asynchronously.

Reduce the number of threads you use to a minimum!

 

AppDomains

AppDomain is an independent application running environment

It is a logical space and a thing between threads and processes. When a. NET process appears, the. NET process will load the necessary things, create an AppDomain, and implement multithreading in the AppDomain.

AppDomain provides the ability to separate applications, uninstall applications, and provide security boundaries when executing managed code.

For example, when our Hello World Program is loaded, the. NET Framework CLR will create a SystemDomain for us. This SystemDomain will load mscorlib, that is, Microsoft's core Runtime Library. This core Runtime Library runs in SystemDomain and creates a SharedDomain, which loads the Assembly in GAC. Finally, create a Domain0 to load the interface thread or the main thread.

All managed code is executed in AppDomain.

Multiple application domains can be executed in a process.

There is no one-to-one correspondence between application domains and threads.

One application domain can have multiple threads

A thread can run in one application domain or between multiple application domains.

 

Demonstration 3

AppDomain and thread

When the Save button is clicked, It is clicked in the main thread. A new thread is created in the main thread to execute EmulateReallyLongProcess in the new thread. In this method, another thread is created to call the DoneDelegateHandler method asynchronously. There are three threads in total.

This example is similar to the preceding example. When a button in a form is pressed, another thread can work, we also want to update the interface elements of the current form, but our method is not inside the current interface. That is to say, if the EmulateReallyLongProgress method wants to change the elements in the Form, we can only use Delegate for callback. After callback, we can use Private Members of the transform class.

 

Framework class library

Public namespace

System

System. Data

System. Data. Xml

Other Namespaces

System. Windows. Forms

System. Web

System. Configuration

System. IO

System. Security

 

Attribute of a program)

Attribute is a number of. NET classes. It can add some original data to IL to describe some attributes of the program. These attributes are identified during compilation.

Attributes can be used to describe any of the following types: Assembly, Module, Property, Field, Event, Interface, Parameter, Delegate, ReturnValue

Attribute can be searched by writing code at runtime, and can be used to control code execution.

Many Attributes are embedded in the Framework.

You can also compile some of your own attributes by deriving from System. Attribute.

 

CLSCompliantAttribute

It is used to specify whether the current program or Code complies with the Common Language Runtime specification (CLS)

This Attribute only applies to assembly, module, type, or type members.

If the CLSCompliantAttribute label is not used, the compiler defaults:

The Assembly is CLS incompatible

If a type is CLS compatible, all types or assemblies it contains must be CLS compatible.

If a member of a type is CLS compatible, the member type must be CLS compatible.

 

Data Type

Reference Type

Must be instantiated before use

Class

Allocate in managed heap

Value Type

No default constructor (instantiation is not required)

Primitives: Integer, float, string, and byte

Structure

Allocate memory in the stack

 

Demonstration 4

Data Type

C # is case-sensitive. The only difference between the first function and the third function is case-sensitive. After these methods are compiled into IL in the C # environment, these three functions can be effectively differentiated. However, if the three functions are compiled in the VB environment, VB is case-insensitive and an error is returned. Therefore, this method is not compatible with CLS.

When we add the CLSCompliant label in AssemblyInfo, that is, we require CLS compatibility, and an error will be reported even in the C # environment.

Four errors are displayed. The main errors are: UInte32 is not CLS compatible; the two functions are case-insensitive and not CLS compatible, because some languages are case-insensitive.

 

Versioning)

Use strong names in programming Sets

Use the tool sn.exe to generate a strong-named (strong-name) key file (containing key pairs)

The key file contains the key pair (Public Key and private key). When the application compiles and signs the key, the private key is extracted from the key file, implement certain inverse columns for the Application Assembly signature. After the column is reversed, the application has certain characteristics. because others do not have your private key, only you can sign it. Then, save the public key of the key file generated by the sn in the application set. When other Assembly calls this strongly-named assembly, it verifies the validity of the Private Key signature with the public key attached to the application and assembly.

You can use the AssemblyKeyFile tag to compile the strongly-named key into the application assembly.

Strong naming can be used to confirm the Assembly version and install the Assembly into Global Assembly Catch (GAC ).

 

Demonstration 5

Versioning

Use the sn-k Command

Key generated successfully

Use strong naming

When an application assembly is strongly named, it also requires that the other Assembly referenced by it be strongly named.

Strong naming ensures that the Code is not tampered. Once the code is tampered with, it also ensures the validity of the code version.

When we change * in the version number to a fixed value

In addition, it is required that the reference of the main Project to the sub-Project is directly from the path to select the dll file reference, rather than the Project reference. (For Project reference, VS will automatically update the version of the entire Assembly for us)

After the compilation is successful, we will change the version of only one subitem to 1.0.0.1.

After this sub-project is compiled successfully and the main project is not compiled, we replace the compiled dll of version 1.0.0.0 in the bin folder of the main project.

Then we directly execute the application and use the Sub-item Function of the updated version in it. At this time, the incorrect version of the application assembly is displayed.

 

Reflection (Reflection)

System. Runtime. Reflection namespace

Reflection can be used to obtain metadata information at runtime.

Find the type and metadata in the PE file (assembly)

Dynamic usage type during runtime

 

Demonstration 6

Reflection

This is a simple About form.

Assembly. GetExecutingAssembly can get the currently executed application Assembly, and then get the information of the current application Assembly through GetCustomAttributes. These application assembly information is set in AssemblyInfo.

In this way, the corresponding assembly information can be read from the About form at runtime.

 

The List displays information about other currently running assemblies, which are obtained using the following code:

GetEntryAssembly obtains all the currently running loaded assemblies, and GetReferenceAssemblies obtains the assembly of the current application.

 

Framework programming

Framework class library

Collections

Arrays

Enums

IEnumerable interface and Foreach (For Each)

You can use Foreach to traverse members by implementing the IEnumerable interface.

Runtime information

Reflection

Assembly attributes and labels

AppDomain

 

String

The content of the string is fixed, immutable (unchangeable)

That is, once a string is formed, it cannot be changed.

Concatenate a small number of strings. We recommend that you use String. Format ()

If you use a large number of + to connect strings, the performance will be compromised.

Use System. Text. StringBuilder to connect a large number of strings

AppendFormat () method of StringBuilder

 

Demonstration 7

String

Concatenate a string with the output, using System. diagnostics. trace. writeLine can easily output debugging information, which is especially useful for multi-threaded debugging, because multithreading may cause some problems when setting breakpoints.

Main Function

Output panel

 

Summary

. NET Framework contains a series of reusable components divided by namespaces.

MSIL, PE

Attribute can be used to customize the metadata or description information of various elements in an assembly.

Reflection can get the type in the Assembly at runtime, which can conveniently implement the plug-in Function

2010.10.7

Related Article

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.