IDisposable pattern usage in C #

Source: Internet
Author: User
Tags call back ftp client

In this paper, the use of IDisposable mode in C # is described, and the recycling of garbage resources is explained in detail. Share it for everyone's reference. Here's how:

First, for garbage collection, in C #, the garbage collection of managed resources is implemented through the CLR's garbage collection, garbage collection calls the destructor of the object on the stack to complete the release of the object, and for some unmanaged resources, such as database link object, need to implement IDisposable interface for manual garbage collection. So when to use the IDisposable interface, and how to use it?

First, refer to the following code:

public interface idisposable{  void Dispose (); public class disposablclass:idisposable{  //whether to recover the  bool _disposed;  public void Dispose ()  {    Dispose (true);    Gc. SuppressFinalize (this);  }  ~disposableclass ()  {    Dispose (false);  }  The parameters here indicate whether the managed object that implements the IDisposable interface needs to be freed  protected virtual void Dispose (bool disposing)  {    if (_ disposed) return; If it has been reclaimed, it interrupts execution if    (disposing)    {      //todo: Releases the managed object that implements the IDisposable interface    }    //todo: Releases unmanaged resources, Set object to null    _disposed = true;}  }


Dispose () method

Call the Dispoase () method when you need to reclaim the Disposableclass class for an unmanaged resource. This method is not automatically called by the CLR and needs to be called manually.


~disposableclass (), destructor

When an object on the managed heap is not referenced by another object, the GC invokes the object's destructor before it reclaims the object. The meaning of the ~disposableclass () destructor here is to tell the GC that you can reclaim me, and Dispose (false) means that you do not need to recycle manually when GC is recycled.


Virtual method Dispose (bool disposing)

With this approach, all managed and unmanaged resources can be recycled. The parameter disposing indicates whether the managed object that implements the IDisposable interface needs to be freed.

If Disposings is set to true, it means that the Disposablclass class relies on some managed objects that implement the IDisposable interface, which can be obtained through the Dispose (bool disposing) Method calls the Dispose () method of these managed objects for recycling.

If Disposings is set to false, it means that the Disposableclass class is dependent on some unmanaged resources that do not implement IDisposable, then set these unmanaged resource objects to null. Wait for the GC to call the Disposableclass class's destructor to reclaim these unmanaged resources.

In addition, the above

The reason for setting the Dispose (bool disposing) method to protected virtual is that you want subclasses to be able to participate in the design of garbage collection logic together, without affecting the base class

。 For example, there is a subclass of this type:

public class subdisposableclass:diposableclass{  private bool _disposed;//Indicates whether it has been reclaimed  protected override void Dispose (bool disposing)  {if    (!_disposed)//If not yet reclaimed    {if      (disposiing)//If you need to reclaim some managed resources      {        // TODO: Reclaim managed resources, call IDisposable's Dispose () method to      //todo: Reclaim unmanaged resources, set it to null, wait for the CLR to call the destructor when recycling      _disposed = true;    }    Base. Dispose (disposing);//Call Back the garbage collection logic of the Parent class  }}


Before. NET 2.0, if an object's destructor throws an exception, the exception is ignored by the CLR. However, after. NET 2.0, if the destructor throws an exception, it causes the application to crash. Therefore, it is important to ensure that destructors do not throw exceptions.

Also, does the Dispose () method allow exceptions to be thrown? The answer is in the negative.

If the Dispose () method has the potential to throw an exception, then you need to use Try/catch to manually capture

。 Here are some possible ways to think about the Dispose () method:

public class disposableclass:idisposable{  bool _disposed;  ......  protected virtual void Dispose (bool disposing)  {    if (_disposed) return;    if (disposing)    {      //todo: Call the managed resource's Dispose () method for garbage collection    }    try    {      _channelfactory.close (); There may be exceptions when you close the    }    catch (Exception ex)    {      _log. Warn (ex);//record log      try      {        _channelfactory.abort ();//may have an exception when discarded      }      catch (Exception CeX)      {        _log. Warn (CeX);//record Log      }    }    _channelfactory = null;    _disposed = true;}  }


Summarize:


When we reference some managed and unmanaged resources in our custom classes and their business logic, we need to implement the IDisposable interface to implement garbage collection of these resource objects.

It is hoped that this article will help you achieve high-efficiency C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
IDisposable pattern usage in C #

This address: http://www.paobuke.com/develop/c-develop/pbk23539.html






Related content C # Implementation of the FTP client case Ò???? édˉ′???? Ó??? ¢μ???????? ¢?òmessageboxex daily Collection C # interface Knowledge (knowledge Comprehensive) C # Implementation of control camera class
C # Modify and reset the computer password DirectoryEntry implementation Method C # ensures that only one instance in the running method C # traverses the list and removes an element of the method C # WinForm captures unhandled exception instance resolution

IDisposable pattern usage in C #

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.