C # Resource release and Dispose, Close method

Source: Internet
Author: User

Need to be clear about the C # program (or. NET). Simply put, each type in C # represents a resource, and resources fall into two categories:

Managed resource: A resource that is allocated and freed by the CLR, that is, a new object from the CLR;

Unmanaged resources: Objects that are not managed by the CLR, Windows kernel objects such as files, database connections, sockets, COM objects, and so on;

Without exception, if our type uses unmanaged resources, or if we need to explicitly release managed resources, we need to have the type inherit the interface IDisposable. This is tantamount to telling the caller that the type needs to explicitly release the resource, and you need to call my Dispose method.

However, all this is not so simple, a standard type that inherits the IDisposable interface should be implemented as follows. This implementation we call the Dispose pattern: public class sampleclass:idisposable
{
Demo Create an unmanaged resource
Private IntPtr Nativeresource = Marshal.allochglobal (100);
Demo Create a managed resource
Private Anotherresource Managedresource = new Anotherresource ();
private bool disposed = false;

<summary>
Implementing the Dispose method in IDisposable
</summary>
public void Dispose ()
{
Must be True
Dispose (TRUE);
Notifies the garbage collection mechanism to no longer invoke finalizers (destructors)
Gc. SuppressFinalize (this);
}

<summary>
is not necessary, and provides a close method only to conform to the specifications of other languages (such as C + +)
</summary>
public void Close ()
{
Dispose ();
}

<summary>
Must, in case the programmer forgets to call the Dispose method explicitly
</summary>
~ SampleClass ()
{
Must be false
Dispose (FALSE);
}

<summary>
Protected virtual for non-sealing type modification
Seal type decoration with private
</summary>
<param name= "disposing" ></param>
protected virtual void Dispose (bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
Cleaning up Managed resources
if (Managedresource!= null)
{
Managedresource.dispose ();
Managedresource = null;
}
}
Cleaning Up Unmanaged Resources
if (Nativeresource!= IntPtr.Zero)
{
Marshal.freehglobal (Nativeresource);
Nativeresource = IntPtr.Zero;
}
Let the type know that he has been released
disposed = true;
}

public void Samplepublicmethod ()
{
if (disposed)
{
throw new ObjectDisposedException ("SampleClass", "SampleClass is disposed");
}
Omitted
}
}

In the Dispose mode, almost every row has a special meaning.

In the standard dispose mode, we notice a method that starts with a ~:///<summary>
Must, in case the programmer forgets to call the Dispose method explicitly
</summary>
~ SampleClass ()
{
Must be false
Dispose (FALSE);
}

This method is called a type terminator. The whole point of providing finalizers is that we cannot expect that the type of caller will definitely invoke the Dispose method, which is invoked by the garbage collector, and the finalizer is used as a remedy for resource release.

A Dispose method of a type should be allowed to be invoked multiple times without throwing an exception. For this reason, the type internally maintains a private Boolean variable disposed:

private bool disposed = false;

In the actual method of handling code cleanup, the following judgment statement is added: if (disposed)
{
return;
}
Omit the cleanup part code and assign the disposed to true at the end of the method
disposed = true;

This means that if the type is cleaned up once, the cleanup will no longer work.

It should be noted that in the standard Dispose mode, the Dispose method that really implements the IDisposable interface has no actual cleanup work, and it actually calls the following protected virtual method with Boolean parameters:///<summary>
Protected virtual for non-sealing type modification
Seal type decoration with private
</summary>
<param name= "disposing" ></param>
protected virtual void Dispose (bool disposing)
{
Omitting code
}

Such a protected virtual method is provided to account for situations in which this type is inherited by other classes. If the type has a subclass, subclasses may implement their own Dispose mode. A protected virtual method is used to remind a subclass that it must be aware of the cleanup of the parent class when implementing its own cleanup method, that is, the subclass needs to call base in its own release method. Dispose method.

Also, we should have noticed that the virtual method that really writes the resource release code has a Boolean parameter. This argument is provided because we differentiate between managed and unmanaged resources when resources are released.

In the parameterless Dispose method of an explicitly freed resource that is invoked by the caller, the calling parameter is True:public void Dispose ()
{
Must be True
Dispose (TRUE);
Other omitted
}

This indicates that the code will handle both managed and unmanaged resources at the same time.

The invocation parameter is false: ~ SampleClass () in the finalizer for an implicit cleanup resource that is invoked by the garbage collector.
{
Must be false

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.