Effective C# 学习笔记(一):Implement the Standard Dispose Pattern

1. The standard dispose idiom frees your unmanaged resources using the IDisposable interface when clients remember, and it uses the finalizer defensively when clients forget. It works with the Garbage Collector to ensure that your objects pay the performance penalty associated with finalizers only when necessary. 

 

2. The root base class in the class hierarchy should implement the IDisposable interface to free resources.

Implementing IDisposable is the standard way to inform users and the runtime system that your objects hold resources that must be released in a timely manner

The implementation of your IDisposable.Dispose() method is responsible for four tasks:

1.Freeing all unmanaged resources.

2.Freeing all managed resources (this includes unhooking events).

3.Setting a state flag to indicate that the object has been disposed. You need to check this state and throw ObjectDisposed exceptions in your public methods, if any get called after disposing of an object.

4.Suppressing finalization. You call GC.SuppressFinalize(this) to accomplish this task.

You accomplish two things by implementing IDisposable: You provide the mechanism for clients to release all managed resources that you hold in a timely fashion, and you give clients a standard way to release all unmanaged resources. 

 

3. This type should also add a finalizer as a defensive mechanism.

 

 

4. Both of these routines delegate the work of freeing resources to a virtual method that derived classes can override for their own resource-management needs.

protected virtual void Dispose(bool isDisposing);

This overloaded method does the work necessary to support both finalize and Dispose, and because it is virtual, it provides an entry point for all derived classes. Derived classes can override this method, provide the proper implementation to clean up their resources, and call the base class version. You clean up managed and unmanaged resources when isDisposing is True; clean up only unmanaged resources when isDisposing is false. In both cases, call the base class's Dispose(bool) method to let it clean up its own resources.

Example:

View Code
1.       public class MyResourceHog : IDisposable

2.        {

3.            // Flag for already disposed

4.            private Boolean alreadyDisposed = false;

5.            // finalizer:

6.            // Call the virtual Dispose method.

7.            ~MyResourceHog()

8.            {

9.                Dispose(false);

10.            }

11.            // Implementation of IDisposable.

12.            // Call the virtual Dispose method.

13.            // Suppress Finalization.

14.            public void Dispose()

15.            {

16.                Dispose(true);

17.                GC.SuppressFinalize(true);

18.            }

19.            // Virtual Dispose method

20.            protected virtual void Dispose(Boolean isDisposing)

21.            {

22.                // Don't dispose more than once.

23.                if (alreadyDisposed)

24.                    return;

25.                if (isDisposing)

26.                {

27.                    // TODO: free managed resources here.

28.                }

29.                // TODO: free unmanaged resources here.

30.                // Set disposed flag:

31.                alreadyDisposed = true;

32.            }

33.       }

If a derived class needs to perform additional cleanup, it implements the protected Dispose method:

View Code
1.      public class DerivedResourceHog : MyResourceHog

2.        {

3.            // Have its own disposed flag.

4.            private Boolean disposed = false;

5.            protected override void Dispose(Boolean isDisposing)

6.            {

7.                // Don't dispose more than once.

8.                if (disposed)

9.                    return;

10.                if (isDisposing)

11.                {

12.                    // TODO: free managed resources here.

13.                }

14.                // TODO: free unmanaged resources here.

15.                // Let the base class free its resources.

16.                // Base class is responsible for calling

17.                // GC.SuppressFinalize( )

18.                base.Dispose(isDisposing);

19.                // Set derived class disposed flag:

20.                disposed = true;

21.            }

22.         }

Notice that both the base class and the derived class contain a flag for the disposed state of the object. This is purely defensive. Duplicating the flag encapsulates any possible mistakes made while disposing of an object to only the one type, not all types that make up an object. 

 

5. The derived classes need override the virtual method only when the derived class must free its own resources and it must remember to call the base class version of the function.

 

6. the most important recommendation for any method associated with disposal or cleanup: You should be releasing resources only. 

 

你可能感兴趣的:(effective)