Dispose c# là gì

  -  

This article describes the differences between the Dispose & Finalize methods in C# and when to lớn use each when managing resources.

Bạn đang xem: Dispose c# là gì


*
by

Although the .NET framework frees managed memory và resources transparently, it"s not as adept at freeing unmanaged resources; you have khổng lồ help it out by implementing the Dispose and Finalize patterns in your code. When the .NET framework instantiates an object, it allocates memory for that object on the managed heap. The object remains on the heap until it"s no longer referenced by any active code, at which point the memory it"s using is "garbage," ready for memory deallocation by the .NET Garbage Collector (GC). Before the GC deallocates the memory, the framework calls the object"s Finalize() method, but developers are responsible for calling the Dispose() method.

The two methods are not equivalent. Even though both methods persize object clean-up, there are distinct differences between them. To design efficient .NET applications, it"s essential that you have a proper understanding of both how the .NET framework cleans up objects and when and how to use the Finalize & Dispose methods. This article discusses both methods và provides code examples & tips on how và when to lớn use them.

An Insight Inkhổng lồ the Dispose and Finalize Methods

The .NET garbage collector manages the memory of managed objects (native .NET objects) but it does not manage, nor is it directly able to lớn clean up unmanaged resources. Managed resources are those that are cleaned up implicitly by the garbage collector. You bởi not have to write code khổng lồ release such resources explicitly. In contrast, you must clean up unmanaged resources (tệp tin handles, database collections, etc.) explicitly in your code.

There are situations when you might need lớn allocate memory for unmanaged resources from managed code. As an example, suppose you have sầu to open a database connection from within a class. The database connection instance is an unmanaged resource encapsulated within this class & should be released as soon as you are done with it. In such cases, you"ll need to miễn phí the memory occupied by the unmanaged resources explicitly, because the GC doesn"t miễn phí them implicitly.Briefly, the GC works as shown below:

It searches for managed objects that are referenced in managed code. It then attempts khổng lồ finalize those objects that are not referenced in the code. Lastly, it frees the unreferenced objects và reclaims the memory occupied by them.

The GC maintains lists of managed objects arranged in "generations." A generation is a measure of the relative sầu lifetime of the objects in memory. The generation number indicates khổng lồ which generation an object belongs. Recently created objects are stored in lower generations compared to lớn those created earlier in the application"s life cycle. Longer-lived objects get promoted lớn higher generations. Because applications tkết thúc lớn create many short-lived objects compared khổng lồ relatively few long-lived objects, the GC runs much more frequently lớn clean up objects in the lower generations than in the higher ones.

Xem thêm: Bột Mì Tinh Là Gì - Cách Nhận Biết Hai Loại Bột Này

Keep this information about the .NET garbage collector in mind as you read the remainder of the article. I"ll walk you through the Finalize method first, và then discuss the Dispose method.

Finalizers—Implicit Resource Cleanup

Finalization is the process by which the GC allows objects khổng lồ clean up any unmanaged resources that they"re holding, before actually destroying the instance. An implementation of the Finalize method is called a "finalizer." Finalizers should không tính phí only external resources held directly by the object itself. The GC attempts to điện thoại tư vấn finalizers on objects when it finds that the object is no longer in use—when no other object is holding a valid reference khổng lồ it. In other words, finalizers are methods that the GC calls on "seemingly dead objects" before it reclaims memory for that object.The GC calls an object"s finalizer automatically, typically once per instance—although that"s not always the case. The framework calls finalizers on a secondary thread handled by the GC. You should never rely on finalizers to clean up managed resources. A class that has no finalizer implemented but is holding references to lớn unmanaged objects can cause memory leaks, because the resources might become orphaned if a class instance is destroyed before releasing the unmanaged objects.

You must implement finalizers very carefully; it"s a complex operation that can carry considerable performance overhead. The performance overhead stems from the fact that finalizable objects are enlisted và removed from the finalization queues, which are internal data structures containing pointers to lớn instances of classes that implement a finalizer method. When pointers khổng lồ these objects are placed in this data structure, the object is said khổng lồ be enlisted in the Finalization Queue. Note that the GC periodically scans this data structure khổng lồ locate these pointers. When it finds one, it removes the pointer from the queue and appends the pointer at the kết thúc of another queue called the reachable queue.

Further, finalizable objects tend to lớn get promoted lớn the higher generations and hence stay in memory for a relatively longer period of time. Note that the GC works more frequently in the lower generations than in the higher ones.

Xem thêm: Người Mệnh Mộc Kỵ Màu Gì Khắc Màu Gì Và Lời Giải Đáp Trọn Vẹn

The time & order of execution of finalizers cannot be predicted or pre-determined. This is why you"ll hear that the nature of finalization is "non-deterministic." Further, due to the non-deterministic nature of finalization the framework does not & cannot guarantee that the Finalize method will ever be called on an instance. Hence, you cannot rely upon this method to lớn free up any unmanaged resources (such as a tệp tin handle or a database connection instance) that would otherwise not be garbage collected by the GC.

cảnh báo that you cannot Điện thoại tư vấn or override the Finalize method. It is generated implicitly if you have sầu a destructor for the class. This is shown in the following piece of C# code: