Object pooling and caching are very useful object-orented patterns. They work well for large or hardweight objects. For example, you can store GDI+ pens in some PenStore, which stores its pens in maintained cache. This pattern greatly improves the speed of your code without adding to the object heap’s overhead.
How to Create the Cache
.NET objects are built on a garbage-collected heap. So, we can use weak references to objects to use garbage collector functionality for our needs. Garbage collector does all we need without any lines of code because of its “generations” idiom. It tracks the lifetime of objects and collects garbage when required.
So, if an object was going out of scope, there is a time while an object is still alive and can be reused by the cache. (It is true also in the case of using of an object in other threads.) Yet another aspect of the Cache pattern in the .NET world is determining whether the object has been disposed. It matters because no one wants to work with disposed objects (if it supports IDisposable).
There is no generic .NET way to determine whether this object has been disposed, but some other ways exist (the Control.IsDisposed method, for example). The IDisposableEx interface helps to determine your object’s state (look at the attached Disposable class for details).
How to Represent the Cache
The cache looks like a dictionary. So, we can copy the IDictionary interface contract that the cache has agreed to. But we cannot use the IDictionary interface itself because a null value in the cache may be returned sometimes, even when a nonnull value was posted into the cache before (in the case of a value, the object was excluded from the cache in the process of garbage collection).
This behavior looks like none of the dictionaries, so we do not use the cache to implement the IDictionary interface. Our sources are fully self-documented through C# XML documentation tags.
The demo application is included as a download.