Putting the Cache into Action
The
downloadable sample application (see
Figure 1) lets you test the cache, using a very small
Foo test class:
class Foo
{
public String Name;
}
Author's Note: In production, this class wouldn't be a good candidate for caching using weak references because the WeakReference itself could consume more memory than the object that it's referencing. |
 | |
Figure 1. Testing the Cache: The sample application creates and caches a large number of objects and lets you see how many have been garbage collected. |
This is the code that generates the objects:
for (int x = 0; x < 50000; x++)
{
Foo foo = new Foo();
foo.Name = "Bar " + x.ToString();
if (x == 0)
m_foo = foo;
m_cacheManager.Add<Foo>(foo.Name, foo);
}
Here's the output:
Scavenging is starting. There are 40001 items in the list.
Scavenging is Complete. There are 39503 items in the list.
Scavenging is starting. There are 40001 items in the list.
Scavenging is Complete. There are 39502 items in the list.
Scavenging is starting. There are 40001 items in the list.
Scavenging is Complete. There are 39502 items in the list.
Scavenging is starting. There are 40001 items in the list.
Scavenging is Complete. There are 39502 items in the list.
The WeakReference object is very powerful, but—just as Microsoft warns—you must combine it with additional logic to make it useful in a caching application. But you'll find the effort required to take advantage of the CacheReference class worthwhile if you need to distribute events from a service to client objects.