-
Notifications
You must be signed in to change notification settings - Fork 34
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.
The example below shows how to implement exclusive Url access using a lock object per Url.
var urlLocks = new SingletonCache<Url, object>();
Url url = new Url("https://foo.com");
using (var lifetime = urlLocks.Acquire(url))
{
lock (lifetime.Value)
{
// exclusive url access
}
}