处理Azure缓存异常和悲观并发

时间:2013-11-09 01:03:20

标签: c# .net azure

我正在尝试为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;
    }

0 个答案:

没有答案