1

我正在尝试为 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,但我能想到的模拟 a 的唯一另一种方法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;
    }
4

0 回答 0