/// <summary> /// Uses the specified functions to remove a key/value pair from the dictionary if the key exists and passes a condition, or to update a key/value pair in the dictionary if the key exists but does not. /// </summary> /// <param name="key">The key to be removed or whose value should be updated</param> /// <param name="removalConditionFunc">The function used to check if a key should be removed or updated.</param> /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on the key's existing value</param> /// <returns>Whether the key was found and successfully removed or not.</returns> public bool RemoveOrUpdate(TKey key, Func <TKey, TValue, bool> removalConditionFunc, Func <TKey, TValue, TValue> updateValueFactory) { bool blnReturn; using (EnterReadLock.Enter(LockObject)) { if (_dicData.TryGetValue(key, out TValue objExistingValue)) { blnReturn = removalConditionFunc(key, objExistingValue); if (blnReturn) { using (LockObject.EnterWriteLock()) blnReturn = _dicData.Remove(key); } if (!blnReturn) // Not an else in case we somehow fail at removing a key that still passes the condition { using (LockObject.EnterWriteLock()) _dicData[key] = updateValueFactory(key, objExistingValue); } } else { blnReturn = false; } } return(blnReturn); }
/// <inheritdoc /> protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { using (EnterReadLock.Enter(LockObject)) { if (_blnSkipCollectionChanged) { return; } if (e.Action == NotifyCollectionChangedAction.Reset) { _blnSkipCollectionChanged = true; using (LockObject.EnterWriteLock()) { // Remove all duplicate entries for (int intLastIndex = Count - 1; intLastIndex >= 0; --intLastIndex) { T objItem = this[intLastIndex]; for (int intIndex = IndexOf(objItem); intIndex != intLastIndex; intIndex = IndexOf(objItem)) { RemoveAt(intIndex); --intLastIndex; } } } _blnSkipCollectionChanged = false; } } base.OnCollectionChanged(e); }
/// <inheritdoc /> public bool TryTake(out KeyValuePair <TKey, TValue> item) { bool blnTakeSuccessful = false; TKey objKeyToTake = default; TValue objValue = default; // Immediately enter a write lock to prevent attempted reads until we have either taken the item we want to take or failed to do so using (LockObject.EnterWriteLock()) { if (_lstIndexes.Count > 0) { // FIFO to be compliant with how the default for BlockingCollection<T> is ConcurrentQueue objKeyToTake = _lstIndexes[0]; if (_dicUnorderedData.TryGetValue(objKeyToTake, out objValue)) { blnTakeSuccessful = _dicUnorderedData.Remove(objKeyToTake); if (blnTakeSuccessful) { _lstIndexes.RemoveAt(0); } } } } if (blnTakeSuccessful) { item = new KeyValuePair <TKey, TValue>(objKeyToTake, objValue); return(true); } item = default; return(false); }
// ReSharper disable once InheritdocInvalidUsage /// <inheritdoc /> public T this[int index] { get { using (EnterReadLock.Enter(LockObject)) return(_lstOrderedData[index]); } set { using (EnterReadLock.Enter(LockObject)) { T objOldItem = _lstOrderedData[index]; if (objOldItem.Equals(value)) { return; } using (LockObject.EnterWriteLock()) { _setData.Remove(objOldItem); _setData.Add(value); _lstOrderedData[index] = value; } } } }
/// <inheritdoc cref="List{T}.Sort()" /> public async ValueTask SortAsync() { using (await EnterReadLock.EnterAsync(LockObject)) { if (_setData.Comparer is IComparer <T> comparer) { IAsyncDisposable objLocker = await LockObject.EnterWriteLockAsync(); try { _lstOrderedData.Sort(comparer); } finally { await objLocker.DisposeAsync(); } } else { IAsyncDisposable objLocker = await LockObject.EnterWriteLockAsync(); try { _lstOrderedData.Sort(); } finally { await objLocker.DisposeAsync(); } } } }
/// <summary> /// Adds a key/value pair to the dictionary if the key does not already exist, or to update a key/value pair in the dictionary if the key already exists. /// </summary> /// <param name="key">The key to be added or whose value should be updated</param> /// <param name="addValue">The value to be added for an absent key</param> /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on the key's existing value</param> /// <param name="token">Cancellation token to listen to.</param> /// <returns>The new value for the key. This will be either be addValue (if the key was absent) or the result of updateValueFactory (if the key was present).</returns> public async ValueTask <TValue> AddOrUpdateAsync(TKey key, TValue addValue, Func <TKey, TValue, TValue> updateValueFactory, CancellationToken token = default) { using (await EnterReadLock.EnterAsync(LockObject, token)) { IAsyncDisposable objLocker; if (_dicData.TryGetValue(key, out TValue objExistingValue)) { TValue objNewValue = updateValueFactory(key, objExistingValue); objLocker = await LockObject.EnterWriteLockAsync(token); try { token.ThrowIfCancellationRequested(); _dicData[key] = objNewValue; } finally { await objLocker.DisposeAsync(); } return(objNewValue); } objLocker = await LockObject.EnterWriteLockAsync(token); try { token.ThrowIfCancellationRequested(); _dicData.Add(key, addValue); } finally { await objLocker.DisposeAsync(); } return(addValue); } }
public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args) { LockObject t = null; if (_typeLock.TryGetValue(instanceType, out t)) { if (Monitor.TryEnter(t, _acquireLockTimeout)) { try { Debug.WriteLine("Entering for " + instanceType + " Lock: " + t.Guid.ToString()); args.Proceed(); } finally { Debug.WriteLine("Completed blocking" + instanceType + " Lock: " + t.Guid.ToString()); Monitor.Exit(t); } } } else { throw new InvalidOperationException("Lock object not found for " + instanceType); } }
public override void SetLock(LockObject lockObj) { base.SetLock(lockObj); OnVertexSnappingModeChaged(); SetColors(); UpdateColliders(); }
/// <inheritdoc /> public void Dispose() { Mugshot?.Dispose(); DownLoadRunning?.Dispose(); MyPluginDataDic.Dispose(); LockObject?.Dispose(); }
protected virtual void Dispose(bool disposing) { if (disposing) { LockObject.Dispose(); } }
public void CopyFrom(CharacterCache objExistingCache) { using (LockObject.EnterWriteLock()) using (EnterReadLock.Enter(objExistingCache.LockObject)) { _strBackground = objExistingCache.Background; _strBuildMethod = objExistingCache.BuildMethod; _strCharacterAlias = objExistingCache.CharacterAlias; _strCharacterName = objExistingCache.CharacterName; _strCharacterNotes = objExistingCache.CharacterNotes; _strConcept = objExistingCache.Concept; _blnCreated = objExistingCache.Created; _strDescription = objExistingCache.Description; _strEssence = objExistingCache.Essence; _strGameNotes = objExistingCache.GameNotes; _strKarma = objExistingCache.Karma; _strFileName = objExistingCache.FileName; _strMetatype = objExistingCache.Metatype; _strMetavariant = objExistingCache.Metavariant; _strPlayerName = objExistingCache.PlayerName; _strSettingsFile = objExistingCache.SettingsFile; _imgMugshot?.Dispose(); _imgMugshot = objExistingCache.Mugshot.Clone() as Image; } }
/// <summary> /// Use in place of CollectionChanged Subtract /// </summary> /// <param name="objTag">Tag of delegate to remove from CollectionChanged</param> /// <returns>True if a delegate associated with the tag was found and deleted, false otherwise.</returns> public async ValueTask <bool> RemoveTaggedCollectionChangedAsync(object objTag) { IAsyncDisposable objLocker = await LockObject.EnterWriteLockAsync(); try { (bool blnSuccess, HashSet <NotifyCollectionChangedEventHandler> setFuncs) = await _dicTaggedAddedDelegates.TryGetValueAsync(objTag); if (!blnSuccess) { Utils.BreakIfDebug(); return(false); } foreach (NotifyCollectionChangedEventHandler funcDelegateToRemove in setFuncs) { base.CollectionChanged -= funcDelegateToRemove; } setFuncs.Clear(); return(true); } finally { await objLocker.DisposeAsync(); } }
/// <summary> /// Use in place of CollectionChanged Adder /// </summary> /// <param name="objTag">Tag to associate with added delegate</param> /// <param name="funcDelegateToAdd">Delegate to add to CollectionChanged</param> /// <returns>True if delegate was successfully added, false if a delegate already exists with the associated tag.</returns> public async ValueTask <bool> AddTaggedCollectionChangedAsync(object objTag, NotifyCollectionChangedEventHandler funcDelegateToAdd) { IAsyncDisposable objLocker = await LockObject.EnterWriteLockAsync(); try { (bool blnSuccess, HashSet <NotifyCollectionChangedEventHandler> setFuncs) = await _dicTaggedAddedDelegates.TryGetValueAsync(objTag); if (!blnSuccess) { setFuncs = new HashSet <NotifyCollectionChangedEventHandler>(); await _dicTaggedAddedDelegates.AddAsync(objTag, setFuncs); } if (setFuncs.Add(funcDelegateToAdd)) { base.CollectionChanged += funcDelegateToAdd; return(true); } } finally { await objLocker.DisposeAsync(); } Utils.BreakIfDebug(); return(false); }
public LogConfig GetLogConfig(Guid accountId, Guid componentId) { lock (LockObject.ForComponent(componentId)) { var componentService = Context.ComponentService; var component = componentService.GetComponentById(accountId, componentId); var accountDbContext = Context.GetAccountDbContext(accountId); var repository = accountDbContext.GetLogConfigRepository(); var config = repository.GetByComponentId(componentId); if (config == null) { config = new LogConfig() { Enabled = true, ComponentId = component.Id, LastUpdateDate = DateTime.Now, IsDebugEnabled = true, IsTraceEnabled = true, IsInfoEnabled = true, IsWarningEnabled = true, IsErrorEnabled = true, IsFatalEnabled = true }; repository.Add(config); } return(config); } }
protected virtual async ValueTask DisposeAsync(bool disposing) { if (disposing) { await LockObject.DisposeAsync(); } }
private static void TryRemoveLock(string name, LockObject o) { if (o.LockCountAdd(-1).LockCount == 0) { LockDict.TryRemove(name, out _); } }
/// <summary> /// Adds a key/value pair to the dictionary if the key does not already exist, or to update a key/value pair in the dictionary if the key already exists. /// </summary> /// <param name="key">The key to be added or whose value should be updated</param> /// <param name="addValue">The value to be added for an absent key</param> /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on the key's existing value</param> /// <returns>The new value for the key. This will be either be addValue (if the key was absent) or the result of updateValueFactory (if the key was present).</returns> public async ValueTask <TValue> AddOrUpdateAsync(TKey key, TValue addValue, Func <TKey, TValue, TValue> updateValueFactory) { using (await EnterReadLock.EnterAsync(LockObject)) { IAsyncDisposable objLocker; if (_dicData.TryGetValue(key, out TValue objExistingValue)) { TValue objNewValue = updateValueFactory(key, objExistingValue); objLocker = await LockObject.EnterWriteLockAsync().ConfigureAwait(false); try { _dicData[key] = objNewValue; } finally { await objLocker.DisposeAsync().ConfigureAwait(false); } return(objNewValue); } objLocker = await LockObject.EnterWriteLockAsync().ConfigureAwait(false); try { _dicData.Add(key, addValue); } finally { await objLocker.DisposeAsync().ConfigureAwait(false); } return(addValue); } }
public void GetByGuid() { var lockObj = new LockObject(1000); var guid1 = new Guid("5A79EF6A-F8DF-496B-BB64-5C3B7F8E61A3"); var guid2 = Guid.Parse("5A79EF6A-F8DF-496B-BB64-5C3B7F8E61A3"); var guid3 = guid2; // копия структуры var guid4 = new Guid("51094EE8-30F5-49EC-9A5A-94ABA9E56A8A"); var obj1 = lockObj.Get(guid1); var obj2 = lockObj.Get(guid2); var obj3 = lockObj.Get(guid3); var obj4 = lockObj.Get(guid4); Assert.True(ReferenceEquals(obj1, obj2)); Assert.True(ReferenceEquals(obj1, obj3)); Assert.False(ReferenceEquals(obj1, obj4)); int count = 100; for (int i = 0; i < count; i++) { var g1 = Guid.NewGuid(); var g2 = Guid.Parse(g1.ToString()); var g3 = g1; var o1 = lockObj.Get(g1); var o2 = lockObj.Get(g2); var o3 = lockObj.Get(g3); Assert.True(ReferenceEquals(o1, o2)); Assert.True(ReferenceEquals(o1, o3)); } }
/// <inheritdoc cref="Dictionary{TKey, TValue}.Clear" /> public void Clear() { using (LockObject.EnterWriteLock()) { _dicUnorderedData.Clear(); _lstIndexes.Clear(); } }
/// <inheritdoc /> public void Add(TKey key, TValue value) { using (LockObject.EnterWriteLock()) { _dicUnorderedData.Add(key, value); _lstIndexes.Add(key); } }
public virtual void SetLock(LockObject lockObj) { if (lockObj == null) { lockObj = new LockObject(); } m_lockObj = lockObj; }
public async Task GetLock_MissingLock_ReturnsNull() { string id = _idGenerator.Next(34000, 49999).ToString(); string lockCategory = _uniqueKeys.GetKey("GBLI"); LockObject missing = await _locker.GetLock(lockCategory, id); Assert.IsNull(missing); }
private static void ReleaseLockObject(object key, LockObject lockObj) { lockObj.Counter--; lock (LockPool) { if (lockObj.Counter == 0) { LockPool.Remove(key); } } }
private void SetDefaultEventHandlers() { using (LockObject.EnterWriteLock()) { _onMyDoubleClick += OnDefaultDoubleClick; _onMyKeyDown += OnDefaultKeyDown; _onMyContextMenuDeleteClick += OnDefaultContextMenuDeleteClick; } }
/// <summary> /// /// </summary> /// <param name="lockObject"></param> /// <param name="expiry"></param> /// <returns></returns> public bool Lock(LockObject lockObject, TimeSpan expiry) { Throws.ArgumentNullException(lockObject, nameof(lockObject)); if (this._memoryCache.Get(lockObject.Key) != null) { return(false); } return(this._memoryCache.Set(lockObject.Key, lockObject.Value, expiry)); }
public LoopObject(LockObject locker, int lower, int upper, int modulus, int threads) { this.locker = locker; this.lower = lower; this.upper = upper; this.modulus = modulus; this.amountOfThreads = threads; CreateThreads(threads); }
private void ReturnLockObject(LockObject lockObject) { lock (_lockTable) { if (lockObject.Close()) { _lockTable.Remove(lockObject.GetKey()); } } }
static void OpenLockObject() { if (instance != null) { instance.Close(); } instance = EditorWindow.CreateInstance <LockObject>(); instance.Show(); }
/// <summary> /// Throws exception when metadata could not be converted to a valid PDFDocument instance. /// </summary> /// <param name="library"></param> /// <param name="data"></param> /// <param name="library_items_annotations_cache"></param> /// <returns></returns> public static PDFDocument LoadFromMetaData(Library library, byte[] data, Dictionary <string, byte[]> /* can be null */ library_items_annotations_cache) { DictionaryBasedObject dictionary = PDFMetadataSerializer.ReadFromStream(data); LockObject _lock = new LockObject(); PDFDocument pdf_document = new PDFDocument(_lock, library, dictionary); // thread-UNSAFE access is permitted as the PDF has just been created so there's no thread-safety risk yet. pdf_document.doc.GetAnnotations(library_items_annotations_cache); return(pdf_document); }
public EventType GetOrCreate(EventType eventType, Guid accountId) { var lockObj = LockObject.ForEventType(accountId, eventType.SystemName); lock (lockObj) { var repository = GetEventTypeRepository(accountId); return(repository.GetOrCreate(eventType)); } }
public CountLoop(LockObject locker, int lower, int upper, int modulus, int threads) : base(locker, lower, upper, modulus, threads) { this.counter = 0; action = (int i) => { counter++; }; }
public ListLoop(LockObject locker, int lower, int upper, int modulus, int threads) : base(locker, lower, upper, modulus, threads) { list = new LinkedList<int>(); action = (int i) => { list.AddLast(i); }; }
public KeyValuePair <TKey, TValue> this[int index] { get { using (EnterReadLock.Enter(LockObject)) return(new KeyValuePair <TKey, TValue>(_lstIndexes[index], _dicUnorderedData[_lstIndexes[index]])); } set { using (EnterReadLock.Enter(LockObject)) { if (_dicUnorderedData.TryGetValue(value.Key, out TValue objOldValue)) { int intOriginalIndex = _lstIndexes.IndexOf(value.Key); if (index == intOriginalIndex) { return; } TKey objKeyToRemove = _lstIndexes[index]; using (LockObject.EnterWriteLock()) { _lstIndexes[index] = value.Key; for (int i = intOriginalIndex; i < _lstIndexes.Count - 2; ++i) { if (i != index) { _lstIndexes[i] = _lstIndexes[i + 1]; } } _lstIndexes.RemoveAt(_lstIndexes.Count - 1); if (objKeyToRemove != null) { _dicUnorderedData.Remove(objKeyToRemove); } if (!objOldValue.Equals(value.Value)) { _dicUnorderedData[value.Key] = value.Value; } } } else { using (LockObject.EnterWriteLock()) { TKey objKeyToRemove = _lstIndexes[index]; _dicUnorderedData.Remove(objKeyToRemove); _dicUnorderedData.Add(value.Key, value.Value); _lstIndexes[index] = value.Key; } } } } }
private static LockObject GetLockObject(object key) { lock (LockPool) { var lockObj = LockPool[key] as LockObject; if (lockObj == null) { lockObj = new LockObject(); LockPool[key] = lockObj; } lockObj.Counter++; return lockObj; } }
/// <summary> /// �ͷ�������, ���������ü���Ϊ0ʱ, ����������Ƴ� /// </summary> /// <param name="key"></param> /// <param name="lockObj"></param> private static void ReleaseLockObject(object key, LockObject lockObj) { lockObj.Counter--; lock (_lockPool) { //Console.WriteLine(string.Format("I am thread {0}:lock counter is {1}", Thread.CurrentThread.Name, lockObj.Counter)); if (lockObj.Counter == 0) { _lockPool.Remove(key); } } }
public SearchLoop(LockObject locker, int lower, int upper, int modulus, int threads, string hash) : base(locker, lower, upper, modulus, threads) { answer = -1; stop = false; this.hash = hash; action = (int i) => { answer = i; stop = true; }; }
LoopObject CreateLoop(LockObject locker, ProgramMode programMode) { switch (programMode) { case ProgramMode.Count: return new CountLoop(locker, lower, upper, modulus, threads); case ProgramMode.List: return new ListLoop(locker, lower, upper, modulus, threads); case ProgramMode.Search: return new SearchLoop(locker, lower, upper, modulus, threads, hash); default: throw new NotImplementedException(); } }
public IDisposable AcquireLock(string key) { LockObject obj; lock (keyLocksLock) { if (!keyLocks.TryGetValue(key, out obj)) { keyLocks[key] = obj = new LockObject(key); } obj.Withdraw(); } Monitor.Enter(obj); return new DisposableToken(this, obj); }
public DisposableToken(StringLock stringLock, LockObject lockObject) { this.stringLock = stringLock; this.lockObject = lockObject; }