我正在尝试为Azure缓存中的对象实现悲观并发逻辑。以下是我正在摆弄的代码:
public SyncObject GetOperatorSync(int operatorId)
{
DataCacheLockHandle handle = null;
SyncObject sync;
string key = OpPrefix + operatorId;
try
{
sync = (SyncObject) _cache.GetAndLock(key, _cacheTimeOut, out handle);
}
catch (DataCacheException ex)
{
if (ex.ErrorCode == DataCacheErrorCode.ObjectLocked)
{
return GetOperatorSync(operatorId);
}
throw;
}
finally
{
if (null != handle)
_cache.Unlock(key, handle);
}
return sync;
}
我不喜欢在catch
中进行递归调用,但我能想到的另一种模拟lock
的方法是将bool值设置为false并运行一个while
循环。
像这样:
public SyncObject GetOperatorSync(int operatorId)
{
DataCacheLockHandle handle = null;
SyncObject sync = null;
string key = OpPrefix + operatorId;
bool isLocked = true;
while (isLocked)
{
try
{
sync = (SyncObject)_cache.GetAndLock(key, _cacheTimeOut, out handle);
isLocked = false;
}
catch (DataCacheException ex)
{
if (ex.ErrorCode != DataCacheErrorCode.ObjectLocked)
{
throw;
}
}
finally
{
if (null != handle)
_cache.Unlock(key, handle);
}
}
return sync;
}