Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Caching with Weak References in .NET : Page 3

Caching can help minimize network traffic when building service-oriented architecture applications; unfortunately, Microsoft's Caching Application Block falls short in a few areas.


advertisement
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&lt;Foo&gt;(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.



Rich Quackenbush is lead software engineer for Vitech Corporation. He has been developing software for 10 years and has worked on a broad range of products.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap