IDisposable and Managed Resources

Possible duplicate:
Proper use of the IDisposable interface

I have a class that has both managed and unmanaged resources. I use IDisposable to release unmanaged resources. Should I free managed resources in the delete method? Or can I leave it in the GC to release managed resources?

+1
source share
2 answers

If you look at the following documentation , you will find the line:

  • Free any available resources that belong to the type in your Dispose method.

Thus, in your allocation method, you must manage managed resources that also implement IDisposable. If the object does not implement this, you do not need to delete it.

+3
source

I would suggest that classes with finalizers (the C # compiler generates finalizers for any classes with destructors) should avoid references to any objects that will not be used in finalization. With relatively few exceptions, classes that store resources that are encapsulated in objects should avoid using resources that are not so encapsulated. Instead, these resources should be encapsulated in their own objects, so they can be held together with other objects containing the resources.

Once this has been taken care of, the correct behavior for any class that owns resources that are encapsulated in other objects usually causes Dispose on all such resources within its own Dispose method, and not to implement a finalizer (and - for C # - not have a destructor, which will cause the compiler to create a finalizer). If the finalizer runs on an object that contains other objects that need to be finalized, each of these objects is usually in one of three states:

  • The finalizer on this other object will already be running, in which case you don’t need to do anything to clear it.
  • The finalizer on this other object will be launched, and in this case, probably, nothing needs to be done to clear it.
  • Other strong links may exist for this other object, in which case it still cannot be cleared.

Only in the second case will there be any reason to think about how to do the cleaning at another facility.

Note, by the way, that the garbage collector almost never has to rely on doing anything other than the free memory directly consumed by the object instances. Deterministic removal is almost always much better. The only thing that you ever need to consciously use the garbage collector to clean up resources is when you are going to create relatively inexpensive resources that are known to be effectively cleaned during garbage collection, and instances will be widely shared that figuring out when the last one leaves the scope, otherwise it would be impractical. Despite the fact that sometimes it is advisable to refuse disposable items, refusing disposable items without justification is always a mistake (if it is appropriate to refuse disposable items, this justifies one of the reasons for this).

+1
source

Source: https://habr.com/ru/post/1241112/


All Articles