You need to clarify the resources in the C # Program (or. NET. Simply put, every type in C # represents a resource, and resources are divided into two categories:
Managed resources: Resources allocated and released by CLR management, that is, new objects in CLR;
Unmanaged resources: objects not managed by CLR, windows kernel objects, such as files, database connections, sockets, and COM objects;
Without exception, if our types Use unmanaged resources, or we need to explicitly release managed resources, we need to let the type inheritance interface IDisposable. This is equivalent to telling the caller that this type requires explicit resource release and you need to call my Dispose method.
However, this is not so simple. A standard that inherits the type of the IDisposable interface should be implemented as follows. This implementation is called the Dispose mode:
Public ClassSampleClass: IDisposable
{
//Demonstrate creating an unmanaged Resource
PrivateIntPtr nativeResource=Marshal. AllocHGlobal (100);
//Demonstrate creating a Managed Resource
PrivateAnotherResource managedResource= NewAnotherResource ();
Private BoolDisposed= False;
/// <Summary>
///Implement the Dispose method in IDisposable
/// </Summary>
Public VoidDispose ()
{
//Must be true
Dispose (True);
//Notifies the garbage collection mechanism not to call the terminator (destructor)
GC. SuppressFinalize (This);
}
/// <Summary>
///It is not necessary to provide a Close method only to better comply with the specifications of other languages (such as C ++ ).
/// </Summary>
Public VoidClose ()
{
Dispose ();
}
/// <Summary>
///Required, in case that the programmer forgets to explicitly call the Dispose method
/// </Summary>
~SampleClass ()
{
//Must be false
Dispose (False);
}
/// <Summary>
///Protected virtual for non-seal class Modification
///Private for sealing class Modification
/// </Summary>
/// <Param name = "disposing"> </param>
Protected Virtual VoidDispose (BoolDisposing)
{
If(Disposed)
{
Return;
}
If(Disposing)
{
//Clear managed resources
If(ManagedResource! = Null)
{
ManagedResource. Dispose ();
ManagedResource= Null;
}
}
//Clear unmanaged Resources
If(NativeResource! =IntPtr. Zero)
{
Marshal. FreeHGlobal (nativeResource );
NativeRes