C # using Garbage collection explanation

Source: Internet
Author: User

Introduction defines a scope that will release one or more objects outside this scope. Syntax using (font font1 = new Font ("Arial", 10.0f)) {}c# Language Reference the primary use using keyword has two main uses: As a statement used to define a range, the end of this range will release the object C # through. NET Framewor The K Common language runtime (CLR) automatically frees memory for storing objects that are no longer needed. The release of memory is uncertain; Once the CLR decides to perform a garbage collection, it frees up memory. However, it is often best to release limited resources such as file handles and network connections as soon as possible. The using statement allows the programmer to specify when an object that uses resources should release resources. The object provided for the using statement must implement the IDisposable interface. This interface provides the Dispose method, which frees the resources for this object. You can exit the using statement when you reach the end of a using statement, or if an exception is thrown before the statement ends and control leaves the statement block. 1. You can declare an object in the using statement (as shown above), or declare the object before the using statement, as follows:
Fontfont2=newfont ("Arial",10.0f);using(font2) {//Usefont2}//2. Multiple objects can be used with a using statement, but these objects must be declared inside the using statement, as follows:using(Fontfont3=newfont ("Arial",10.0f), Font4=newfont ("Arial",10.0f)){//usefont3andfont4.}

Example 1

The following example shows how a user-defined class can implement its own Dispose behavior. Note the type must inherit from IDisposable.
Usingsystem;classc:idisposable{publicvoiduselimitedresource () {Console.WriteLine ("  Usinglimitedresource ... " );} Voididisposable.dispose () {Console.WriteLine ("disposinglimitedresource. " );}} Classprogram{staticvoidmain () {using(cc=newc ()) {C.uselimitedresource ();} Console.WriteLine ("nowoutsideusingstatement. " ); Console.ReadLine ();}}

As an instruction

Used to create aliases for namespaces or to import type ① defined in other namespaces. Allows you to use a type in a namespace so that you do not have to qualify a type's use in that namespace: Using System.text;②. Creates an alias for a namespace or type. Using Project = PC.      Mycompany.project;      The scope of the using directive is limited to the file containing it.      Create a using alias to make it easier to qualify identifiers to namespaces or types. Create a using directive to use the type in the namespace without having to specify a namespace.      The using directive does not give you access to any namespaces that are nested within the specified namespace. Namespaces are divided into two categories: User-defined namespaces and system-defined namespaces. A user-defined namespace is a namespace defined in code. Example 21 to view a system-defined namespace for a column. The following example shows how to define and use a using alias for a namespace:
namespacepc{//Defineanaliasforthenestednamespace.usingproject=PC. MYCOMPANY.PROJECT;CLASSA{VOIDM () {//UsethealiasProject.myclassmc=Newproject.myclass ();}} namespacemycompany{namespaceproject{publicclassmyclass{} }}}2The following example shows how to define a using directive and a using alias for a class://Cs_using_directive2.cs//usingdirective.Usingsystem;//Usingaliasforaclass.usingaliastomyclass=namespace1.myclass;namespacenamespace1{publicclassmyclass{publicoverridestringtostring () {return"Youareinnamespace1.myclass";}}} namespacenamespace2{classmyclass{}}namespacenamespace3{//usingdirective:UsingNameSpace1;//usingdirective:Usingnamespace2;classmainclass{staticvoidmain () {Aliastomyclasssomevar=Newaliastomyclass (); Console.WriteLine (Somevar); }}}

Output: You is in Namespace1.myclass

========================================================================================= in-depth discussion of the introduction. NET family, many of the keywords assume a variety of roles, such as the New keyword is a number of jobs, in addition to the ability to create objects, hide base class members in the inheritance system, and in the generic declaration constraints may be used as the parameters of the type parameters, in detail on the basis of the use of multiple identities to understand. NET is simple and profound in language mechanism. So, what are the various aspects of using multiple identities, and let's start with a glimpse of it: · Introduction to Namespaces · Create aliases · Forcing resource cleanup below, this article will explain the use of colorful applications from these angles. The usage rules for introducing namespaces using as the introduction of namespace directives are: using Namespace; in. NET programs, the most common code is to introduce the System namespace at the beginning of a program file. The reason for this is that many of the most basic and common operations are encapsulated in the System namespace, and the following code is most familiar to us: using System, so that we can use the type in the namespace directly in the program without having to specify a verbose type name. The using directives can access nested namespaces. About: The namespace namespace is. NET program, rather than the actual physical structure, is a way of avoiding class name collisions, which is used to divide different types of data. For example, many of the basic types in. NET are in the System namespace, the data manipulation type is located in the System.Data namespace, and the misunderstanding · Using a Java-like import directive is a logical structure that introduces a namespace (called a package in Java) and differs from the # include directive in the C language for introducing the actual class library. Using the introduction of a namespace does not equal the assembly in which the namespace is loaded when the compiler compiles, the load of the assembly is determined by whether there is a call operation on the assembly in the program, and if no call operation exists in the code, the compiler will not load the assembly in which the using introduction namespace is located. Therefore, the introduction of multiple namespaces at the beginning of the source file, rather than loading multiple assemblies, does not cause the "over-referencing" disadvantage. The usage rules for using the create aliases for namespaces are: Using alias = Namespace | Type, where namespace represents the alias that created the namespace, and type represents the creation of the type alias. For example, in. NET Office apps, Microsoft.Office.Interop.Word.dll assemblies are often introduced, in order to avoid tedious type input when introducing namespaces, we typically create aliases for them as follows: using MSWord = Microsoft.Office.Interop.Word; You can replace the Microsoft.Office.Interop.Word prefix with MSWord in your program, and if you want to create application objects, you can do so, private static msword.application ooo = New Msword.application (); Similarly, you can create aliases of types by using the following: Another important reason for creating aliases is that the same name types are included in different namespaces introduced in the same CS file, in order to avoid name collisions that can be resolved by setting aliases. such as: 
namespaceboyspace{ Public classPlayer { Public Static voidPlay () {System.Console.WriteLine ("Boys play football."); }   }}namespacegirlspace{ Public classPlayer { Public Static voidPlay () {System.Console.WriteLine ("Girls play violin."); }   }}

Creating an alias with a using, effectively resolves this possible naming conflict, although we can differentiate it by the type's full name, but this is obviously not the best solution, and using makes it easy to solve the problem without any effort, and it also seems to be more compliant with coding requirements in coding specifications.

Forcing resource Cleanup 4.1 The origin to understand clearly using a using statement to force cleanup of resources begins with understanding the Dispose pattern, and understanding the Dispose pattern should be understood first. NET's garbage collection mechanism. These are obviously not the harangues upon that this article can accomplish, we just need to be clear first. NET provides the dispose pattern to implement the ability to explicitly release and close objects. The dispose mode, Dispose mode, is a convention that is provided by. NET to explicitly clean up object resources for freeing unmanaged resources encapsulated by objects in. Net. Because unmanaged resources are not controlled by GC, the object must call its own Dispose () method to release, which is known as the Dispose pattern. From a conceptual point of view, the Dispose pattern is a convention that enforces resource cleanup, and from an implementation point of view, the Dispose pattern is to allow a type to implement the IDisposable interface, allowing the type to provide a public dispose method. This article no longer discusses how to enable a type to implement the Dispose pattern to provide a way to display cleanup of unmanaged resources, focusing on how to use the using statement to easily apply this type of resource cleanup that implements the Dispose pattern. We will have a detailed discussion in the section on memory management and garbage collection. The using statement provides a convenient way to enforce cleanup of object resources, allowing you to specify when to dispose of resources for an object, typically for the following applications:
using(Font f =NewFont ("Verdana", A, Fontstyle.regular)) {//perform text drawing operationsGraphics g =E.graphics; Rectangle rect=NewRectangle (Ten,Ten, $, $); g.DrawString ("Try finally dispose font.", F, brushes.black, rect);}//run end, Release F object Resource

font The object must implement the IDispose interface in order to use the using statement to force the object to clean up resources. We look at its type definition:

Public sealed class Font:marshalbyrefobject, ICloneable, ISerializable, Idisposablefont type did implement the Idisposeable interface, It also has the ability to display recycled resources. However, we do not see from the above code any hint of using the Dispose method, what is the simplicity of this formal using statement, and what is the essence of it? 4.2 In essence to understand the execution nature of the using statement, to understand what the compiler is doing behind the scenes, you must return to the IL code to reveal it:. method public hidebysig static void Main () CIL managed{. entrypoint//code size (0x28). Maxstack 4.locals Init ([0] class [System.drawing]system.drawing.font f,[1] bool cs$4$0000) IL _0000:nopil_0001:ldstr "Verdana" IL_0006:ldc.r4 12.il_000b:ldc.i4.0il_000c:newobj instance void [System.Drawing] System.drawing.font::.ctor (String,float32,valuetype [System.drawing]system.drawing.fontstyle) IL_0011: stloc.0.try{... Partially omitted ...} End. tryfinally{... Partial omission ... Il_001f:callvirt instance void [mscorlib]system.idisposable::D ispose () IL_0024:nopIL_0025:endfinally}//End HandlerIL_0026:nopIL_0027:ret}//End of method Usingdispose::main Obviously, the compiler automatically makes the using as a try-finally statement, And the Dispose method of the object is called in the finally block to clean up the resource. In the. NET specification, Microsoft recommends that an open person place a type of Dispose () or close () method in the finally block of exception handling. According to theSurface analysis We know that the using statement is implicitly invoking the type of Dispose method, so the following code is exactly equivalent to the example above: Font f2 = new Font ("Arial", fontstyle.bold); try{// Performs a text draw operation Graphics g = new graphics (); Rectangle rect = new Rectangle (Ten, ten, $), g.drawstring ("Try finally Dispose font.", F2, Brushes.black, rect);} Finally{if (F2! = null) ((IDisposable) F2). Dispose ();} 4.3 rules · Using can only be used to implement the type of the IDisposable interface, and the use statement is prohibited for types that do not support the IDisposable interface, or a compile-time error occurs; The using statement is useful for cleaning up a single unmanaged resource, and the cleanup of multiple unmanaged objects is best implemented as try-finnaly because there may be a hidden bug in nested using statements. When an inner using block throws an exception, the object resource of the outer using block cannot be freed. • The using statement supports initializing multiple variables, but only if the types of these variables must be the same, for example:
using New New Pen (Brushes.blue)) {//}

Otherwise, the compilation will not pass. However, there is a workaround to solve this problem, because the type of using statement must implement the IDisposable interface, then you can complete the initialization operation in the following way,

using New Font ("Verdana"new  Pen (brushes.black)) {float  as   as Pen). Brush;}

another way to do this is to use try-finally, regardless of whether the initialized object type is consistent.

· Instead of freeing the object's memory, the Dispose method cleans up the unmanaged resources encapsulated by the object, and the object's memory is still controlled by the garbage collector. The program exits the using block when it reaches the end of the using statement, and it is possible to exit prematurely if an exception is introduced before the end of the statement. The object that is initialized in the using can be declared before the using statement, for example:
New Font ("Verdana"9, fontstyle.regular); using (F3) {// perform text drawing operation }

Conclusion

A simple keyword, a variety of different applications. From a more comprehensive perspective, this paper explains the Using keyword. NET, it is worth noting that this usage is not implemented. NET in all high-level languages, this article is primarily confined to C #.

C # using Garbage collection explanation

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.