IDisposable mode in C,

Source: Internet
Author: User

IDisposable mode in C,

When talking about Garbage Collection, in C #, the Garbage Collection of managed resources is implemented through the CLR Garbage Collection, garbage Collection calls the destructor of objects on the stack to release objects. For some unmanaged resources, such as database linked objects, You need to implement the IDisposable interface for manual Garbage Collection. So when to use the Idisposable interface and how to use it?

 

public interface IDisposable
{
    void Dispose();
}
public class DisposablClass : IDisposable
{
// Whether the collection is completed
    bool _disposed;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    ~DisposableClass()
    {
        Dispose(false);
    }
    
// The parameter table shows whether to release the hosted objects that implement the IDisposable interface.
    protected virtual void Dispose(bool disposing)
    {
If (_ disposed) return; // if it has been recycled, the execution is interrupted.
        if(disposing)
        {
// TODO: Release the hosted objects that implement the IDisposable interface.
        }
// TODO: releases unmanaged resources and sets the object to null.
        _disposed = true;
    }
}

 

Dispose () method

Call the Dispoase () method to reclaim the DisposableClass class of unmanaged resources. This method is not automatically called by CLR and needs to be called manually.

 

~ DisposableClass (), destructor

When the objects on the managed Stack are not referenced by other objects, GC calls the object's destructor before reclaiming the objects. Here ~ The significance of DisposableClass () destructor is to tell the GC that you can recycle me. Dispose (false) indicates that manual collection is not required during GC collection.

 

Virtual method Dispose (bool disposing)

In this way, all managed and unmanaged resources can be recycled. The disposing parameter indicates whether to release the hosted objects that implement the IDisposable interface.

 

If disposings is set to true, it indicates that the DisposablClass class depends on some managed objects that implement the IDisposable interface. You can use the Dispose (bool disposing) method to call the Dispose () of these managed objects () method.

 

If disposings is set to false, it indicates that the DisposableClass class depends on some unmanaged resources that do not implement IDisposable. Then, these unmanaged resource objects are set to null, wait for the GC to call the destructor of the DisposableClass class and reclaim these unmanaged resources.

 

In addition, the reason for setting the Dispose (bool disposing) method to protected virtual is that a subclass can be involved in the design of the garbage collection logic together, without affecting the base class. For example, there is a subclass like this:

public class SubDisposableClass : DiposableClass
{
Private bool _ disposed; // indicates whether it has been recycled
    protected override void Dispose(bool disposing)
    {
If (! _ Disposed) // if it has not been recycled
        {
If (disposiing) // if You Need To reclaim some managed resources
            {
// TODO: reclaim managed resources and call the IDisposable Dispose () method.
            }
// TODO: reclaim unmanaged resources and set it to null. Wait until the CLR calls the destructor.
            _disposed = true;
        }
Base. Dispose (disposing); // call 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 CLR. However, if the Destructor throws an exception after. NET 2.0, the application will crash. Therefore, it is very important to ensure that the Destructor does not throw exceptions.


Also, can the Dispose () method throw an exception? The answer is no. If the Dispose () method throws an exception, you need to use try/catch to manually capture it. The following describes the possible Dispose () method exceptions:

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 (); // an exception may occur when it is disabled.
        }
        catch(Exception ex)
        {
_ Log. Warn (ex); // record the log
            try
            {
_ ChannelFactory. Abort (); // exceptions may occur when discarded.
            }
            catch(Exception cex)
            {
_ Log. Warn (cex); // logs are recorded.
            }
        }
        _channelFactory = null;
        _disposed = true;
    }
}

 

Conclusion: when some managed and unmanaged resources are referenced in custom classes and their business logic, we need to implement the IDisposable interface to recycle the garbage of these resource objects.

 

References:

Http://www.cnblogs.com/lori/p/3535470.html
Http://lostechies.com/chrispatterson/2012/11/29/idisposable-done-right/


& In C Language

& Can be used as the bitwise AND or address fetch Operator
The following describes two usage methods:
1. bitwise and operation bitwise AND operator "&" are binary operators. Its function is the binary phase corresponding to the two numbers involved in the operation. The result bit is 1 only when the two binary numbers are 1. Otherwise, the result bit is 0. The number of involved operations is supplemented.
For example, 9 & 5 can be written as follows: 00001001 (Binary complement of 9) & 00000101 (Binary complement of 5) 00000001 (Binary complement of 1) Visible 9 & 5 = 1.
Bitwise AND operations are usually used to clear some bits or retain some bits. For example, if a clears the high eight bits of 0 and retains the low eight bits, it can be used as a & 255 operation (255 of the binary number is 0000000011111111 ).
2. Get the address
& As The unary operator, the result is the address of the right operation object.
For example, & x returns the address of x.
The address itself is an abstract concept used to indicate the logical location of an object in the memory.

& In C Language

& Can be used as the bitwise AND or address fetch Operator
The following describes two usage methods:
1. bitwise and operation bitwise AND operator "&" are binary operators. Its function is the binary phase corresponding to the two numbers involved in the operation. The result bit is 1 only when the two binary numbers are 1. Otherwise, the result bit is 0. The number of involved operations is supplemented.
For example, 9 & 5 can be written as follows: 00001001 (Binary complement of 9) & 00000101 (Binary complement of 5) 00000001 (Binary complement of 1) Visible 9 & 5 = 1.
Bitwise AND operations are usually used to clear some bits or retain some bits. For example, if a clears the high eight bits of 0 and retains the low eight bits, it can be used as a & 255 operation (255 of the binary number is 0000000011111111 ).
2. Get the address
& As The unary operator, the result is the address of the right operation object.
For example, & x returns the address of x.
The address itself is an abstract concept used to indicate the logical location of an object in the memory.

Related Article

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.