Thursday, July 15, 2010

Old dogs can learn new tricks

About a year ago I wrote about using generics and creating thread-safe access to the Web Cache in ASP.NET. In that example I used a pattern that I had copied from some example code and used the classes Type itself to lock the block of code.

lock (typeof(CacheUtils)) {...}

I've since learned this is a bad idea (not a Really Bad Idea but bad enough). After reading articles like Don't Lock Type Objects and Safe Thread Synchronization I've realized the errors of my ways. The better pattern is to use an internal lightweight objects. For example:

private static readonly object locker = new object();
lock (locker) {...}

No comments: