我曾经调用该Put(Key, Value)
方法在 Azure 缓存中设置数据。后来我了解到这种方法可能会导致写入过程中出现竞争条件,并介绍了以下代码用于将数据设置到缓存中。
try
{
if (GetData(key) == null)
{
_cache.Add(key, "--dummy--");
}
DataCacheLockHandle lockHandle;
TimeSpan lockTimeout = TimeSpan.FromMinutes(1);
_cache.GetAndLock(key, lockTimeout, out lockHandle);
if (ttlInMinutes == 0)
{
_cache.PutAndUnlock(key, value, lockHandle);
}
else
{
TimeSpan ttl = TimeSpan.FromMinutes(ttlInMinutes);
_cache.PutAndUnlock(key, value, lockHandle, ttl);
}
}
catch (Exception e)
{}
这涉及两个 IO,而不是前一个调用中的一个。应用程序代码中真的需要这种锁定吗?Azure 的缓存框架是否没有考虑缓存一致性?在 Azure 中管理缓存写入的标准方法是什么?何时使用 Put 以及何时使用 PutAndUnlock?