Skip to content

SingletonCache

Alex Peck edited this page Sep 20, 2022 · 3 revisions

SingletonCache enables mapping every key to a single instance of a value and keeps the value alive only while it is in use. This is useful for caching lock objects or semaphores, where a bounded cache may remove an item while in use resulting in an invalid program state. SingletonCache can be used when the total number of keys is large, but few will be in use at any moment.

SingletonCache doesn't implement the common cache interface and instead provides a simple Acquire then dispose API. The example below shows how to implement exclusive Url access using a lock object per Url:

var uriLocks = new SingletonCache<Uri, object>();

Uri uri = new Uri("https://foo.com");

using (var lifetime = uriLocks.Acquire(uri))
{
   lock (lifetime.Value)
   {
      // exclusive uri access
   }
}