Recommendation 50: Treat managed and unmanaged resources differently in Dispose mode
The virtual method of the real resource release code is a bool parameter with this parameter because we want to differentiate between managed and unmanaged resources when the resource is released.
The call parameter is true in the parameterless Dispose method that is provided to the caller to invoke the explicit dispose of the resource:
Public void Dispose () { // must be true Dispose (true); // omit other code }
This indicates that the code will handle both managed and unmanaged resources at this time.
False is called in the finalizer for an implicit cleanup resource that is called by the garbage collector:
~SampleClass () { // must be false Dispose (false); }
This indicates that when an implicit cleanup is available, the unmanaged resources are processed as long as they are handled.
Why treat managed and unmanaged resources differently? Before this question, let's first understand: Does the managed resource need to be cleaned manually? You might want to divide the types in C # into two categories, one inheriting the IDisposable interface, and one without inheritance. The former, temporarily known as the non-ordinary type, the latter is called the ordinary type. Non-trivial type because it contains an unmanaged resource, it needs to inherit the IDisposable interface, but this contains the type itself of the unmanaged resource, which is a managed resource. Therefore, a normal type in a managed resource does not need to be cleaned manually, rather than a normal type that needs to be cleaned manually (that is, the Dispose method is called).
The idea of the Dispose pattern design is that if the caller explicitly calls the Dispose method, the type should release its own resources in a step-by-step manner. If the caller forgets to call the Dispose method, then the type assumes that all of its managed resources (even those that are not normal) are all given to the garbage collector for recycling, so no manual cleanup is performed. So in the Dispose method, the virtual method passes in the parameter true, and in the finalizer, the virtual method passes in the parameter false.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs-Recommendation 50: Treat managed and unmanaged resources differently in Dispose mode