The gc mechanism of. Net has two problems: GC cannot release all resources, and it cannot release unmanaged resources. Second, GC is not real-time, and there is uncertainty in All GC.
To solve this problem,. NET provides destructor
Public class disposeclass: system. idisposable {// The Public void dispose () method explicitly called by the programmer {// call the parameter-based dispose method to release the managed and unmanaged resource dispose (true ); // If you manually call dispose to release resources, the Destructor is unnecessary. In this case, GC is prevented from calling the destructor system. GC. suppressfinalize (this);} // The dispose method of protected to ensure that it is not called externally. // Pass in the bool value disposing to determine whether to release the Managed Resource Protected void dispose (bool disposing) {If (disposing) {// todo: add the code for clearing "managed resources" here, which should be xxx. dispose () ;}/// todo: add the code for clearing "unmanaged resources" Here} // destructor for GC calls ~ Disposeclass () {dispose (false); // release unmanaged resources }}
Even if we forget to call dispose when appropriate, GC will help us clean up unmanaged resources when releasing objects. The role played by GC is only a means of protection. It should act as such a role, and we cannot rely too much on it. In fact, when a large module exits, we should also manually call GC. Collect in time for garbage collection.