46. Interface IDisposable should be inherited to release resources
class SampleClass : IDisposable { //Show me how to create an unmanaged resource private IntPtr nativeResource = Marshal.AllocHGlobal(100); //Show me how to create a managed resource private AntherResource manageResource = new AntherResource(); private bool disposed = false; /// <summary> ///Implement Dispose method in IDisposable /// </summary> public void Dispose() { //Must be true Dispose(true); //Tell gc to stop calling the finalizer (destructor) GC.SuppressFinalize(this); } /// <summary> ///It is not necessary to provide a Close method just to conform to the specifications of other languages (such as C + +) /// </summary> public void Close() { Dispose(); } /// <summary> ///Required, the placement programmer forgot to display the call to Dispose method /// </summary> ~SampleClass() { //Must be false Dispose(false); } /// <summary> ///protected virtual for unsealed class decoration ///private for sealing class decoration /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { //Clean up managed resources if(manageResource != null) { manageResource.Dispose(); manageResource = null; } } //Clean up unmanaged resources if(nativeResource != IntPtr.Zero) { Marshal.FreeHGlobal(nativeResource); nativeResource = IntPtr.Zero; } //Let the type know that they have been released disposed = true; } public void SamplePublicMethod() { if (disposed) { throw new ObjectDisposedException("SampleClass", "SampleClass is disposed"); } } }
Yes
47. Even if the display release method is provided, implicit cleanup should be provided in the destructor
As written in the above code, to prevent forgetting to call
48. The Dispose method should be allowed to be called multiple times without throwing exceptions
Maybe after the manual call, the terminator calls again, as shown in the above code
49. A protected virtual method should be extracted in Dispose mode
50. Managed resources and unmanaged resources should be treated differently in Dispose mode
51. Type with releasable field or type with unmanaged type resource should be releasable
That is to say, if class A contains unmanaged resources and class B combines class A, then class B should also implement the Dispose mode
52. Release resources in time
Open a file or byte stream or something. Just use using. It will release resources in time after using