C# Disposable pattern, Dispose Vs Finalize

36
2



Discussed below topics
1) What is Finalize and how to create ?
2) What is Destructor and purpose?
3) IDisposable interface
3) Using block
4) What is GC.Collect?
5) Why and when to use GC.suppressfinalize
6) Dispose Vs Finalize
7) GC Performance differences between Dispose or Finalize.

Nguồn:https://wijstaanvooronzegrondrechten.org/

36 COMMENTS

  1. Note for myself: dùng GC.SuppressFinalize(this) để kêu GC đừng có chạy cái logic trong Finalize aka Destructor (ví dụ như đừng có đẩy object this này vô cái Finalize queue rồi GC sẽ deallocate unmanaged memory)

    Để ý trong Détructor() chỉ có logic để deallocate unmanaged memory thôi. Còn trong Dispose() chỉ có logic để deallocate managed memory thôi, và phải call SuppressFinalize() để GC đừng đụng gì đến unmanaged mem.

  2. What happens to an object when usually we don’t provide a Destructor? How is it different with when we explicitly provide a Destructor?

  3. Hi, why should we use dispose for managed code, if the GC automatically free the heap memory if the instance is not referring by any object in stack? Please explain sir

  4. Well explained.. Have a question.. when a class has Destructor GC will move the object to Finalize queue. Let's say user forgot to call the Dispose. Finalize will be called which will call Dispose(false) which will clear only unmanaged code. In this case how GC will clear the managed objects(object is in Finalize queue). Will the object comes back to Gen 0/1 once the Destructor is called?
    Thanks

  5. Awesomeee Sir,

    Reallyyy made it easy to understand,

    Now I can face this question anytime 🙂

    Thanks a lot Sir.

    Expecting more such concepts clearing videos from you.

  6. Dispose just executes the code inside, it will NOT release the current object itself unlike the finalize. Note that for finalize, finalize is called just before the object is to be released.

  7. Thank you so very much!!!! Finally I got finalize and dispose in my head, I had read many blogs but all were confusing…Thanks again..

LEAVE A REPLY

Please enter your comment!
Please enter your name here