Understanding of managed and unmanaged resources, hosting of managed resources
In the. net programming environment, system resources are divided into managed resources and unmanaged resources.
For the collection of managed resources, manual intervention is not required, and you cannot intervene in the collection. All you can do is to understand how. net CLR performs these operations. That is to say, for most objects created by your application, you can use the. NET Framework Garbage Collector to implicitly execute all necessary memory management tasks.
There are two types of resources: managed memory resources, which do not require us to worry about, and the system has managed them for us. For unmanaged resources, here we reiterate that Stream, database connections, related objects of GDI +, and Com objects need to be manually released.
For unmanaged resources, you must release these resources after they are used in the application, such as System. IO. A file object of StreamReader must be closed by calling the Close () method of the object to be displayed. Otherwise, it will occupy the system memory and resources, and unexpected errors may occur.
Here, I want to know what is managed resources and what is non-managed resources? Release.
The most common type of unmanaged resources is the objects that encapsulate operating system resources, such as files, windows, or network connections. For such resources, although the garbage collector can track the lifetime of objects that encapsulate unmanaged resources, however, it does not know how to clear these resources. Fortunately, the. net Framework provides the Finalize () method, which allows you to clear unmanaged resources when the Garbage Collector recycles such resources. If you search for Finalize in the MSDN Library, you will find many similar topics. Here we list several common unmanaged resources: ApplicationContext, Brush, Component, ComponentDesigner, Container,
Context, Cursor, FileStream, Font, Icon, Image, Matrix, Object, OdbcDataReader, OleDBDataReader, Pen, Regex, Socket, StreamWriter, Timer, Tooltip, and other resources. It is possible that many of them did not notice it during use!
About managed resources, we don't need to talk about it, such as simple int, string, float, DateTime, etc. Over 80% of. net resources are managed resources.
How to release unmanaged resources. NET Framework provides the Object. Finalize method, which allows the Object to properly clean up its unmanaged resources when the Garbage Collector recycles the memory used by the Object. By default, the Finalize method does not perform any operations. By default, the Finalize method does not perform any operations. If you want the Garbage Collector to clear the object before it recycles the object's memory, you must override the Finalize method in the class. However, you can find that the override method Finalize () cannot be used in actual programming. In C, you can use the destructor to automatically generate the Finalize method and call the Finalize method of the base class.
For example:
~ MyClass () {// Perform some cleanup operations here.} the code is implicitly translated as the following code. Protected override void Finalize () {try {// Perform some cleanup operations here.} finally {base. Finalize ();}}
However, the override method Finalize () is not recommended in programming, because the implementation of the Finalize method or destructor may have a negative impact on the performance. A simple reason is as follows: using the Finalize method to recycle the memory used by the object requires at least two garbage collections. When the Garbage Collector recycles, it only recycles the Finalize method) in this case, the unaccessible memory with the Finalize method cannot be recycled.
. Instead, it removes the items of these objects from the termination queue and places them in the list of objects marked as "prepared for termination, the items in this list point to the objects in the managed heap that are preparing to be called to terminate the code. The Garbage Collector recycles and releases the memory the next time it recycles.
C # managed and unmanaged Object Management
Objects in C # are classified into value and reference types. The biggest difference between them is the data storage method and storage location. in WINDOWS, the virtual addressing system is used to manage the data storage generated when the program runs. to put it simply, the system manages a memory area and allocates a part of it to store value type variables, called stacks. Stacks adopt the principle of advanced and later release, store value type variables from the highest address bit of the region to the lowest address, first and then, the later-in, first-out management ensures that value-type variables can clear occupied memory even when they are out of scope. Because of the fast stack speed, the stored data is generally not very large, this part generally does not require special user operations. the value type is stored in the stack summary. The stack has very high performance, but it is not flexible for all variables. We usually want to use a method to allocate memory to store some data, and the data can still be used for a long period of time after the method exits. As long as the new operator is used to request a bucket, this possibility exists-for example, all reference types. In this case, use the managed heap. It works under the control of the garbage collector. The managed heap (or heap for short) is another memory area in the large memory area managed by the system. To learn how the heap works and how to allocate memory for the referenced data type, see the following code:
Customer arabel = new Customer ();
This line of code completes the following operations: first, allocate the memory on the stack to store the Customer instance (a real instance, not just an address ). Set the arabel value of the variable to the memory address allocated to the new Customer object (it also calls the fields in the initialization class instance of the appropriate Customer () constructor, but we don't have to worry about this part ).
The Customer instance is not placed in the stack, but in the memory heap. If we do this:
Customer newaddress = arabel;
At this time, newaddress will also be saved in the stack, and its value is the same as that of arabel, which is the heap address for storing the Customer instance.
Once we know this, we will find such a problem. If the arabel and newaddress variables in the stack expire and destroy them, what will happen to the Customer object stored in the stack? In fact, it remains in the heap until the program stops or the Garbage Collector deletes it. if the C # garbage collector does not display a call, it regularly runs and checks the memory to delete data without any variable reference. it looks good, but think about it. The garbage collector does not always check and runs on a regular basis. During this period, if a large amount of expired data is generated, it will reside in the memory ..... then, we can call System. GC. collect (), forces the Garbage Collector to run somewhere in the code, System. GC is a garbage collector. NET base class. The Collect () method calls the garbage collector. However, this method is rarely used. (is it possible to let garbage collection check for memory when an object is destroyed ?) For example, if a large number of objects in the code just stop referencing, it is suitable to call the garbage collector. Besides, the logic of the garbage collector cannot ensure that all expired data is deleted from the heap during a garbage collection process, it is powerless for unmanaged objects (such as file handles, network connections, and database connections) that are not managed by the garbage collector. What should we do?
In this case, you need to develop special rules to ensure that unhosted resources are released when an instance of the recycle class is released.
When defining a category, you can use two mechanisms to automatically release unmanaged resources. These mechanisms are often implemented together because each mechanism provides a slightly different solution to the problem. The two mechanisms are:
● Declare an destructor as a member of the class
● Implement the System. IDisposable interface in the class
Next we will discuss these two mechanisms in sequence, and then introduce how to implement them at the same time to achieve the best results.
Destructor
The previous section describes some operations that a constructor can perform when creating a class instance. When the Garbage Collector deletes an object, it can also call the destructor. Because of this operation, the Destructor seems to be the best place to place the code for releasing unmanaged resources and executing general cleanup operations. However, it is not that simple. The running rules of the spam review determine that the code to run at a certain time cannot be placed in the destructor. If the object occupies valuable and important resources, release these resources as quickly as possible, so you cannot wait for the garbage collector to release them.
IDisposable Interface
We recommend that you use the System. IDisposable interface to replace the destructor. The IDisposable interface defines a mode (with language-level support) and provides a definite mechanism for releasing unmanaged resources, and avoid the inherent problems related to the spam function. The IDisposable interface declares a method Dispose (), which does not contain parameters. The Execution Code of void and Myclass method Dispose () is returned as follows:
class Myclass : IDisposable{ public void Dispose() { // implementation }}
The Execution Code of Dispose () explicitly releases all unmanaged resources directly used by the object, and CALLS Dispose () on all encapsulated objects that implement the IDisposable interface (). In this way, the Dispose () method provides precise control when releasing unmanaged resources.
Suppose there is a class ResourceGobbler, which uses some external resources and executes the IDisposable interface. If you want to instantiate an instance of this class, use it, and then release it, you can use the following code:
ResourceGobbler theInstance = new ResourceGobbler (); // The usage process of theInstance object theInstance. Dispose ();
If an exception occurs during the processing, the Code does not release the resources used by theInstance. Therefore, use the try block to write the following code:
ResourceGobbler theInstance = null; try {theInstance = new ResourceGobbler (); // The usage process of theInstance object} finally {if (theInstance! = Null) theInstance. Dispose ();}
Even if an exception occurs during processing, this version ensures that Dispose () is always called on theInstance and resources used by theInstance are always released. However, if you always need to repeat such a structure, the code will be easily obfuscated. C # provides a syntax to ensure that Dispose () (but not Close () is automatically called on the object when the reference is out of scope ()). This syntax uses the using keyword to complete this job-but currently, it has nothing to do with namespaces in completely different environments. The following code generates the IL code corresponding to the try block:
Using (ResourceGobbler theInstance = new ResourceGobbler () {// The usage process of theInstance object}
The using statement is followed by a pair of parentheses, which are the Declaration and instantiation of referenced variables. This statement places the variables in the included compound statement. In addition, the Dispose () method is automatically called even if an exception occurs when the variable exceeds the scope. If you have already used the try block to capture other exceptions, it will be clearer. To avoid using the using statement, you can only call Dispose () in the finally clause of the existing try block (), you can also avoid extra indentation.
Note:
For some classes, using Close () is more logical than Dispose (), for example, when processing file or database connections. In these cases, the IDisposable interface is often implemented, and an independent Close () method is executed to call Dispose (). This method is clear in class usage and supports the using statement provided by C.
The previous chapter discussed the two methods used by the class to release unmanaged resources:
● Execute the Destructor forcibly executed by the running database, but the execution of the Destructor is uncertain. In addition, due to the way the garbage collector works, it adds unacceptable system overhead to the Runtime Library.
● The IDisposable interface provides a mechanism to allow class users to control the time for resource release, but ensure that Dispose () is executed ().
In general, the best way is to execute these two mechanisms to obtain the advantages of these two mechanisms and overcome their shortcomings. Assume that most programmers can call Dispose () correctly to implement the IDisposable interface, and use the Destructor as a secure mechanism to prevent Dispose () from being called (). The following is an example of dual implementation:
Public class ResourceHolder: IDisposable {private bool isDispose = false; // Pointer to an external unmanaged resource. private IntPtr handle; // Other managed resource this class uses. private Component Components; // display the called Dispose method public void Dispose () {Dispose (true); GC. suppressFinalize (this);} // The actual cleanup method protected virtual void Dispose (bool disposing) {if (! IsDisposed) {if (disposing) {// Delete the managed object here .} // here, execute the CloseHandle (handle); handle = IntPtr operation to clear unmanaged objects. zero;} isDisposed = true;} // destructor ~ ResourceHolder () {Dispose (false );}}
As you can see, Dispose () has the second protected overload method, which includes a bool parameter, which is the method to actually complete the cleaning. Dispose (bool) is called by the Destructor and IDisposable. Dispose. This method focuses on ensuring that all the cleanup code is put in one place.
The parameter passed to Dispose (bool) indicates whether Dispose (bool) is called by the Destructor or by IDisposable. dispose () call -- Dispose (bool) should not be called from other aspects of the Code, the reason is:
● If the customer calls IDisposable. Dispose (), the customer specifies that all resources related to the object should be cleared, including managed and unmanaged resources.
● If the Destructor is called, in principle, all resources still need to be cleared. However, in this case, the Destructor must be called by the garbage collector, and other hosted objects should not be accessed, because we can no longer determine their statuses. In this case, it is best to clear known unmanaged resources, and you want to reference the hosted object and the destructor to execute your own cleaning process.
The isDispose member variable indicates whether the object has been deleted and allows you to delete the member variable multiple times. This simple method is not thread-safe and requires the caller to ensure that there is only one thread to call the method at the same time. It is a reasonable assumption that the customer needs to perform synchronization. This assumption is repeatedly used in the entire. NET class library (for example, in the collection class ). Finally, IDisposable. Dispose () contains a call to the System. GC. SuppressFinalize () method. The SuppressFinalize () method tells the Garbage Collector that a class no longer needs to call its destructor. Because Dispose () has completed all the necessary cleaning work, The Destructor does not need to do any work. Calling SuppressFinalize () means that the Garbage Collector considers this object to have no destructor at all.
Correct understanding of the above content can greatly optimize the system performance and release unnecessary data in a timely manner. instead of relying solely on the automatic recovery mechanism provided by C #, programmers need to use more flexible methods! The combination of the two can not only make the program run fast, but also make the system more stable!