/// <summary> /// This method unlocks the item in the cache using 2 different ways. /// </summary> /// <param name="lockHandle"> The lock handle that was used to lock the item. </param> private static void UnLockItemInCache(LockHandle lockHandle) { _cache.Unlock("Customer:KirstenGoli", lockHandle); //Forcefully unlock item in cache //_cache.Unlock("Customer:KirstenGoli"); }
public void Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock, bool enableRetry) { int retry = _operationRetry; do { try { _cache.Insert(key, item, lockHandle, releaseLock); break; } catch (Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) { throw ex; } retry--; if (_operationRetryDelayInterval > 0) { Thread.Sleep(_operationRetryDelayInterval); } } } while (retry >= 0); }
public static void Run() { // Initialize cache InitializeCache(); // Add item in cache AddItemInCache(); // Create new lock handle to fetch Item usin locking LockHandle lockHandle = new LockHandle(); // Timespan for which lock will be taken TimeSpan timeSpan = new TimeSpan(0, 0, 0, 20); // Get item from cache GetItemFromCache(lockHandle, timeSpan); // Lock Item in cache LockItemInCache(lockHandle, timeSpan); // Unlock item in cache using multiple ways UnLockItemInCache(lockHandle); RemoveItemFromCache(); // Dispose cache once done _cache.Dispose(); }
public bool InsertWithReleaseLock(string key, object value, object lockHandle, Expiration expiration) { if (!Loaded) { return(false); } if (value is byte[]) { value = new ByteArray((byte[])value); } CacheItem item = CreateCacheItem(value, expiration); LockHandle handle = lockHandle as LockHandle; try { cache.Insert(key, item, handle, true); return(true); } catch (Exception ex) { FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not add item to cache due to exception: {0}", ex.Message); return(false); } }
/// <summary> /// This method unlocks the item in the cache using 2 different ways. /// </summary> /// <param name="lockHandle"> The lock handle that was used to lock the item. </param> private static void UnLockItemInCache(string key, LockHandle lockHandle) { _cache.Unlock(key, lockHandle); //Forcefully unlock item in cache //_cache.Unlock(key); }
/// <summary> /// Marks any loaded resources as having been retrieved under a lock if they /// satisfy some predicate. /// </summary> /// <param name="resourceCheck">A function that returns <c>true</c> if the provided resource should be considered retrieved.</param> /// <param name="state">The state object to pass as a second parameter to <paramref name="resourceCheck"/>.</param> /// <returns><c>true</c> if the delegate returned <c>true</c> on any of the invocations.</returns> internal bool SetResourceAsAccessed(Func <TResource, object?, bool> resourceCheck, object?state) { Requires.NotNull(resourceCheck, nameof(resourceCheck)); // Capture the ambient lock and use it for the two lock checks rather than // call AsyncReaderWriterLock.IsWriteLockHeld and IsUpgradeableReadLockHeld // to reduce the number of slow AsyncLocal<T>.get_Value calls we make. // Also do it before we acquire the lock, since a lock isn't necessary. // (verified to be a perf bottleneck in ETL traces). LockHandle ambientLock = this.service.AmbientLock; bool match = false; lock (this.service.SyncObject) { if (ambientLock.HasWriteLock || ambientLock.HasUpgradeableReadLock) { foreach (KeyValuePair <TResource, AsyncReaderWriterResourceLock <TMoniker, TResource> .Helper.ResourcePreparationTaskState> resource in this.resourcePreparationStates) { if (resourceCheck(resource.Key, state)) { match = true; this.SetResourceAsAccessed(resource.Key); } } } } return(match); }
/// <summary> /// This method fetches item from the cache. /// </summary> /// <param name="lockHandle"> An instance of lock handle that will be used for locking the fetched item. </param> /// <param name="timeSpan"> Time for which the lock will be held. </param> private static void GetItemFromCache(string key, LockHandle lockHandle, TimeSpan timeSpan) { // GetT Get<T> (string key, bool acquireLock, TimeSpan lockTimeout, ref LockHandle lockHandle); Customer getCustomer = _cache.Get <Customer>(key, true, timeSpan, ref lockHandle); PrintCustomerDetails(getCustomer); Console.WriteLine("Lock acquired on " + lockHandle.LockId); }
/// <summary> /// This method fetches item from the cache. /// </summary> /// <param name="lockHandle"> An instance of lock handle that will be used for locking the fetched item. </param> /// <param name="timeSpan"> Time for which the lock will be held. </param> private static void GetItemFromCache(LockHandle lockHandle, TimeSpan timeSpan) { // Get Customer getCustomer = (Customer)_cache.Get("Customer:KirstenGoli", timeSpan, ref lockHandle, true); PrintCustomerDetails(getCustomer); Console.WriteLine("Lock acquired on " + lockHandle.LockId); }
/// <summary> /// Releases an exclusive lock for the given key. One must release a lock after first await-ing an /// <see cref="AcquireAsync(TKey)" /> (by disposing the returned lock handle). /// </summary> private void Release(LockHandle handle) { // Release method may be called multiple times for the same LockHandle, // and the method should not be failing for the second call in a raw. if (_exclusiveLocks.TryRemoveSpecific(handle.Key, handle)) { handle.TaskCompletionSource.SetResult(ValueUnit.Void); } }
public static void Main(string[] args) { try { //Initialize cache Cache cache; cache = NCache.InitializeCache("mypartitionedcache"); cache.Clear(); //Locking prevents multiple clients from updating the same data simultaneously //and also provides the data consistency. //Adding an item the cache Customer customer = new Customer(); customer.Name = "Kirsten Goli"; customer.Age = 40; customer.Address = "45-A West Boulevard, Cartago, Costa Rica"; customer.Gender = "Female"; customer.ContactNo = "52566-1779"; cache.Add("Customer:KirstenGoli", customer); //Get TimeSpan timeSpan = new TimeSpan(0, 0, 0, 20); LockHandle lockHandle = new LockHandle(); Customer getCustomer = (Customer)cache.Get("Customer:KirstenGoli", timeSpan, ref lockHandle, true); PrintCustomerDetails(getCustomer); Console.WriteLine("Lock acquired on " + lockHandle.LockId); //Lock item in cache bool isLocked = cache.Lock("Customer:KirstenGoli", timeSpan, out lockHandle); if (!isLocked) { Console.WriteLine("Lock acquired on " + lockHandle.LockId); } //Unlock item in cache cache.Unlock("Customer:KirstenGoli"); //Unlock via lockhandle cache.Unlock("Customer:KirstenGoli", lockHandle); //Must dispose cache cache.Dispose(); Environment.Exit(0); } catch (Exception ex) { Console.WriteLine(ex.Message); Environment.Exit(0); } }
/// <summary> /// This method locks specified item in the cache /// </summary> /// <param name="lockHandle"> Handle of the lock. </param> /// <param name="timeSpan"> Time for which lock will be held. </param> private static void LockItemInCache(string key, LockHandle lockHandle, TimeSpan timeSpan) { // Lock item in cache bool isLocked = _cache.Lock(key, timeSpan, out lockHandle); if (!isLocked) { Console.WriteLine("Lock acquired on " + lockHandle.LockId); } }
/// <summary> /// This method locks specified item in the cache /// </summary> /// <param name="lockHandle"> Handle of the lock. </param> /// <param name="timeSpan"> Time for which lock will be held. </param> private static void LockItemInCache(LockHandle lockHandle, TimeSpan timeSpan) { // Lock item in cache bool isLocked = _cache.Lock("Customer:KirstenGoli", timeSpan, out lockHandle); if (!isLocked) { Console.WriteLine("Lock acquired on " + lockHandle.LockId); } }
/// <summary> /// Faz a liberação do lock de escrita. /// </summary> /// <param name="lockId"></param> public void ReleaseWriterLock(string lockId) { lock (this) { if (_lockMode == LockMode.Write && _writerLock.Equals(lockId)) { _writerLock = null; _lockMode = LockMode.None; } } }
public object GetWithLock(string key, int interval, bool acquireLock, out object lochkHandle) { if (!Loaded) { lochkHandle = null; return(null); } DateTime startTime = DateTime.Now; object value = null; LockHandle handle = null; TimeSpan lockInterval = new TimeSpan(0, 0, 0, 0, interval); while (startTime.AddMilliseconds(interval) >= DateTime.Now) { handle = null; //lochkHandle as LockHandle; if (cache != null) { value = cache.Get(key, lockInterval, ref handle, true); } if (value != null) { break; } if (value == null && handle == null) { break; } Thread.Sleep(500); } if (value == null && handle != null) { if (cache != null) { cache.Unlock(key); value = cache.Get(key, lockInterval, ref handle, true); } } if (value != null) { lochkHandle = handle; } else { lochkHandle = null; } return(value); }
public void Unlock(object key) { var lockHandle = new LockHandle(); if (Get(key.ToString()) != null) { try { cache.Unlock(region, key.ToString(), lockHandle); } catch (CacheException) {} } }
/// <summary> /// Acquires the writer lock on a cache item. Writer lock is acquired only if /// no reader or wirter lock exists on the item. /// </summary> /// <returns>Lockid against which lock is acquired.</returns> public bool AcquireWriterLock(string lockHandle) { lock (this) { if (_lockMode == LockMode.None) { _writerLock = new LockHandle(lockHandle); _lockMode = LockMode.Write; return(true); } } return(false); }
public void Lock(object key) { var lockHandle = new LockHandle(); if (Get(key.ToString()) != null) { try { cache.GetAndLock(region, key.ToString(), TimeSpan.FromMilliseconds(Timeout), out lockHandle); } catch (CacheException) {} } }
/// <summary> /// Tries acquiring an exclusive lock for the given key if available. /// Returns a <see cref="LockHandle"/> or <code>null</code> if lock is already held by another thread. /// </summary> public LockHandle?TryAcquire(TKey key) { var thisHandle = new LockHandle(this, key); LockHandle currentHandle = _exclusiveLocks.GetOrAdd(key, thisHandle); if (currentHandle == thisHandle) { return(thisHandle); } return(null); }
/// <inheritdoc /> public async Task UnlockAsync(object key, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lockHandle = new LockHandle(); if (await(GetAsync(key.ToString(), cancellationToken)).ConfigureAwait(false) != null) { try { cache.Unlock(region, key.ToString(), lockHandle); } catch (CacheException) {} } }
/// <inheritdoc /> public async Task LockAsync(object key, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lockHandle = new LockHandle(); if (await(GetAsync(key.ToString(), cancellationToken)).ConfigureAwait(false) != null) { try { cache.GetAndLock(region, key.ToString(), TimeSpan.FromMilliseconds(Timeout), out lockHandle); } catch (CacheException) {} } }
public override bool Equals(object obj) { LockHandle other = obj as LockHandle; if (other != null && other._lockId == _lockId) { return(true); } else if (obj is string) { return(_lockId == (string)obj); } else { return(false); } }
public object Get(string sessionId, string key, ref LockHandle lockHandle, bool acquireLock, bool enableRetry) { object obj = null; Alachisoft.NCache.Web.Caching.Cache cache = null; _sync.AcquireReaderLock(Timeout.Infinite); try { GetCache(sessionId, key, out obj, null, null, out cache, true, ref lockHandle, acquireLock); return(obj); } finally { _sync.ReleaseReaderLock(); } }
/// <summary> /// Deserializa os dados na instancia. /// </summary> /// <param name="reader"></param> public void Deserialize(CompactReader reader) { _lockMode = (LockMode)reader.ReadByte(); string str = reader.ReadObject() as string; if (!string.IsNullOrEmpty(str)) { _writerLock = new LockHandle(str); } int num = reader.ReadInt32(); _readerLocks = new List <LockHandle>(); for (int i = 0; i < num; i++) { _readerLocks.Add(new LockHandle(reader.ReadObject() as string)); } }
/// <summary> /// Marks a resource as having been retrieved under a lock. /// </summary> internal void SetResourceAsAccessed(TResource resource) { Requires.NotNull(resource, nameof(resource)); // Capture the ambient lock and use it for the two lock checks rather than // call AsyncReaderWriterLock.IsWriteLockHeld and IsUpgradeableReadLockHeld // to reduce the number of slow AsyncLocal<T>.get_Value calls we make. // Also do it before we acquire the lock, since a lock isn't necessary. // (verified to be a perf bottleneck in ETL traces). LockHandle ambientLock = this.service.AmbientLock; lock (this.service.SyncObject) { if (!ambientLock.HasWriteLock && ambientLock.HasUpgradeableReadLock) { this.resourcesAcquiredWithinUpgradeableRead.Add(resource); } } }
public void Insert(string sessionId, string key, CacheItem item, LockHandle lockHandle, bool releaseLock, bool enableRetry) { Alachisoft.NCache.Web.Caching.Cache cache = null; object obj = null; _sync.AcquireReaderLock(Timeout.Infinite); try { GetCache(sessionId, key, out obj, "", "", out cache, false); if (cache != null) { item.Tags = new Runtime.Caching.Tag[] { new Runtime.Caching.Tag(TagUtil.SESSION_TAG) }; cache.Insert(key, item, lockHandle, releaseLock); } } finally { _sync.ReleaseReaderLock(); } }
/// <summary> /// Acquires an exclusive lock for the given key. <see cref="Release" /> must be called /// subsequently in a 'finally' block. /// </summary> public async Task <LockHandle> AcquireAsync(TKey key) { var thisHandle = new LockHandle(this, key); while (true) { LockHandle currentHandle = _exclusiveLocks.GetOrAdd(key, thisHandle); if (currentHandle != thisHandle) { await currentHandle.TaskCompletionSource.Task; } else { break; } } return(thisHandle); }
/// <summary> /// Acquires an exclusive lock for the given key. <see cref="Release" /> must be called /// subsequently in a 'finally' block. /// </summary> public async Task <LockHandle> AcquireAsync(TKey key) { StopwatchSlim stopwatch = StopwatchSlim.Start(); LockHandle thisHandle = new LockHandle(this, key); while (true) { LockHandle currentHandle = _exclusiveLocks.GetOrAdd(key, thisHandle); if (currentHandle != thisHandle) { await currentHandle.TaskCompletionSource.Task; } else { break; } } return(thisHandle.WithDuration(stopwatch.Elapsed)); }
public object Get(string key, ref LockHandle lockHandle, bool acquireLock, bool enableRetry) { object value = null; int retry = _operationRetry; do { try { value = _cache.Get(key, Alachisoft.NCache.Web.Caching.Cache.NoLockExpiration, ref lockHandle, acquireLock); break; } catch (Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) { throw ex; } retry--; if (_operationRetryDelayInterval > 0) { Thread.Sleep(_operationRetryDelayInterval); } } }while (retry >= 0); return(value); }
public object Remove(string sessionId, string key, LockHandle lockHandle, bool enableRetry) { Alachisoft.NCache.Web.Caching.Cache cache = null; object obj = null; _sync.AcquireReaderLock(Timeout.Infinite); try { GetCache(sessionId, key, out obj, "", "", out cache, false); if (cache != null) { return(cache.Remove(key , lockHandle )); } } finally { _sync.ReleaseReaderLock(); } return(null); }
public object Remove(string sessionId, string key, LockHandle lockHandle, bool enableRetry) { object value = null; int retry = _operationRetry; do { try { object removedObj = null; _cache.Remove(key, out removedObj, lockHandle); return(removedObj); } catch (Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) { throw ex; } retry--; if (_operationRetryDelayInterval > 0) { Thread.Sleep(_operationRetryDelayInterval); } } }while(retry >= 0); return(value); }
public void LockedNodeStartChanges(LockHandle lockHandle) { UInt32 status = OpenNIImporter.xnLockedNodeStartChanges(this.InternalObject, lockHandle.InternalHandle); WrapperUtils.CheckStatus(status); }
public void LockedNodeEndChanges(LockHandle lockHandle) { int status = SafeNativeMethods.xnLockedNodeEndChanges(this.InternalObject, lockHandle.InternalHandle); WrapperUtils.ThrowOnError(status); }
public void UnlockForChanges(LockHandle lockHandle) { UInt32 status = OpenNIImporter.xnUnlockNodeForChanges(this.InternalObject, lockHandle.InternalHandle); WrapperUtils.CheckStatus(status); }
public void Deserialize(CompactReader reader) { _lockMode = (LockMode)reader.ReadByte(); string writerLockId = reader.ReadObject() as string; if (!string.IsNullOrEmpty(writerLockId)) _writerLock = new LockHandle(writerLockId); int readLockCount = reader.ReadInt32(); _readerLocks = new List<LockHandle>(); for (int i = 0; i < readLockCount; i++) _readerLocks.Add(new LockHandle(reader.ReadObject() as string)); }
/// <summary> /// Releases a writer lock on the cache item. /// </summary> /// <param name="lockId"></param> public void ReleaseWriterLock(string lockId) { lock (this) { if (_lockMode == LockMode.Write ) { if (_writerLock.Equals(lockId)) { _writerLock = null; _lockMode = LockMode.None; } } } }
/// <summary> /// Acquires the writer lock on a cache item. Writer lock is acquired only if /// no reader or wirter lock exists on the item. /// </summary> /// <returns>Lockid against which lock is acquired.</returns> public bool AcquireWriterLock(string lockHandle) { lock (this) { if (_lockMode == LockMode.None) { _writerLock = new LockHandle(lockHandle); _lockMode = LockMode.Write; return true; } } return false; }