Eddie Garmon's Weblog

some architecture, some c#

July 2008 - Posts

Doh! Synced Actions and Funcs

After a little more use of the Synchronized<T>, I realized that over half the time I was 'returning true' just to satisfy Func<T, bool> when all that was really needed was an Action<T>.

Read, ReadUpgradeableToWrite, and Write are all overloaded now to take either a Action<T> or a Func<T, TReturn>.

You can get the code here.

 

More on Syncronized - upgrade reader to writer

In using my new sync wrapper to clean up a bunch of older code, I came across the need to be able to upgrade from a reader to a writer for certain operations. One example of this it to clean up expired items in my my implementation of a Cache.

protected Synchronized<Dictionary<string, ICacheItem>> _syncDictionary =
    new Synchronized<Dictionary<string, ICacheItem>>(new Dictionary<string, ICacheItem>());
...
private void PurgeExpired() {
    _syncDictionary.ReadUpgradeableToWrite((dictionary, reader) => {
        List<ICacheItem> expired = new List<ICacheItem>();
        foreach (ICacheItem cacheItem in dictionary.Values) {
            if (cacheItem.IsExpired) {
                expired.Add(cacheItem);
            }
        }
        if (expired.Count > 0) {
            reader.UpgradeToWriter();
            foreach (ICacheItem cacheItem in expired) {
                ItemRemovedInternal(cacheItem);
                dictionary.Remove(cacheItem.CacheKey);
            }
        }
        return true;
    });
}

I cleaned up the code a bit, and am making it available here. Free to use, no waranty on fitness.

 

More Posts