我有一个在 Windows Server AppFabric SDK 中找到的 Microsoft.ApplicationServer.Caching.DataCache 对象的扩展方法,如下所示:
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;
namespace Caching
{
public static class CacheExtensions
{
private static Dictionary<string, object> locks = new Dictionary<string, object>();
public static T Fetch<T>(this DataCache @this, string key, Func<T> func)
{
return @this.Fetch(key, func, TimeSpan.FromSeconds(30));
}
public static T Fetch<T>(this DataCache @this, string key, Func<T> func, TimeSpan timeout)
{
var result = @this.Get(key);
if (result == null)
{
lock (GetLock(key))
{
result = @this.Get(key);
if (result == null)
{
result = func();
if (result != null)
{
@this.Put(key, result, timeout);
}
}
}
}
return (T)result;
}
private static object GetLock(string key)
{
object @lock = null;
if (!locks.TryGetValue(key, out @lock))
{
lock (locks)
{
if (!locks.TryGetValue(key, out @lock))
{
@lock = new object();
locks.Add(key, @lock);
}
}
}
return @lock;
}
}
}
目的是让开发人员编写代码,“通过先尝试缓存来获取一些数据。如果缓存中不可用,则执行指定的函数,将结果放入缓存中以供下一个调用者使用,然后返回结果”。像这样:
var data = dataCache.Fetch("key", () => SomeLongRunningOperation());
锁定限制了对单个线程执行可能长时间运行的函数调用,但仅限于同一台机器上的单个进程内。您将如何扩展此模式以使锁定分布式以防止多个进程/机器同时执行该功能?