Exemple #1
0
 /// <summary>
 /// Allow setting the clock interface to be used by the cache.
 /// </summary>
 /// <param name="clock">The clock interface that will be used to determine timestamps.</param>
 public void SetClock(IClock clock)
 {
     using (cacheLock.ReaderLock())
     {
         Clock = clock ?? new DefaultClock();
     }
 }
Exemple #2
0
 public bool exists(string key)
 {
     using (var lk = rwl.ReaderLock())
     {
         return(data.exists(key));
     }
 }
        public async Task LoadTest()
        {
            var rwl      = new AsyncReaderWriterLock();
            var readKeys = new List <IDisposable>();

            for (int i = 0; i != 1000; ++i)
            {
                readKeys.Add(rwl.ReaderLock());
            }
            var writeTask = Task.Run(() => { rwl.WriterLock().Dispose(); });
            var readTasks = new List <Task>();

            for (int i = 0; i != 100; ++i)
            {
                readTasks.Add(Task.Run(() => rwl.ReaderLock().Dispose()));
            }
            await Task.Delay(1000);

            foreach (var readKey in readKeys)
            {
                readKey.Dispose();
            }
            await writeTask;

            foreach (var readTask in readTasks)
            {
                await readTask;
            }
        }
        public async Task LoadTest()
        {
            AsyncReaderWriterLock rwl      = new AsyncReaderWriterLock();
            List <IDisposable>    readKeys = new List <IDisposable>();

            for (int i = 0; i != 1000; ++i)
            {
                readKeys.Add(rwl.ReaderLock());
            }
            Task        writeTask = Task.Run(() => rwl.WriterLock().Dispose());
            List <Task> readTasks = new List <Task>();

            for (int i = 0; i != 100; ++i)
            {
                readTasks.Add(Task.Run(() => rwl.ReaderLock().Dispose()));
            }
            await Task.Delay(1000).ConfigureAwait(false);

            foreach (IDisposable readKey in readKeys)
            {
                readKey.Dispose();
            }
            await writeTask;

            foreach (Task readTask in readTasks)
            {
                await readTask;
            }
        }
        private void DeleteIfNeeded(StringSegment databaseName, Task <DocumentDatabase> database)
        {
            database.ContinueWith(t =>
            {
                // This is in case when an deletion request was issued prior to the actual loading of the database.
                try
                {
                    using (_disposing.ReaderLock(_serverStore.ServerShutdown))
                    {
                        if (_serverStore.ServerShutdown.IsCancellationRequested)
                        {
                            return;
                        }

                        using (_serverStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                            using (context.OpenReadTransaction())
                                using (var rawRecord = _serverStore.Cluster.ReadRawDatabaseRecord(context, databaseName.Value))
                                {
                                    if (rawRecord == null)
                                    {
                                        return;
                                    }

                                    ShouldDeleteDatabase(context, databaseName.Value, rawRecord);
                                }
                    }
                }
                catch
                {
                    // nothing we can do here
                }
            });
        }
Exemple #6
0
 /// <summary>
 /// Set the clock that will be used by the cache to determine when an etry expires.
 /// </summary>
 /// <param name="clock">The clock interface that will be used to determine timestamps.</param>
 public void SetClock(IClock?clock)
 {
     using (cacheLock.ReaderLock())
     {
         Clock = clock ?? new SystemClock();
     }
 }
        public void DeleteIfNeeded(StringSegment databaseName, bool fromReplication = false)
        {
            try
            {
                using (_disposing.ReaderLock(_serverStore.ServerShutdown))
                {
                    if (_serverStore.ServerShutdown.IsCancellationRequested)
                    {
                        return;
                    }

                    using (_serverStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                        using (context.OpenReadTransaction())
                            using (var rawRecord = _serverStore.Cluster.ReadRawDatabaseRecord(context, databaseName.Value))
                            {
                                if (rawRecord == null)
                                {
                                    return;
                                }

                                ShouldDeleteDatabase(context, databaseName.Value, rawRecord, fromReplication);
                            }
                }
            }
            catch
            {
                // nothing we can do here
            }
        }
Exemple #8
0
 protected override void InternalExport(out Entry[] heap, out int count)
 {
     using (myLock.ReaderLock())
     {
         count = this.Count;
         heap  = (Entry[])this.heap.Clone();
     }
 }
Exemple #9
0
        public T this[int index] {
            get {
                using (Lock.ReaderLock()) {
                    return(BackingCollection[index]);
                }
            }

            set {
                using (Lock.WriterLock()) {
                    BackingCollection[index] = value;
                }
            }
        }
Exemple #10
0
 public bool Contains(T item)
 {
     using (_lock.ReaderLock())
     {
         return(_list.Contains(item));
     }
 }
Exemple #11
0
        public async Task ReadLock_WriteLockCanceled_TakesLock()
        {
            var rwl     = new AsyncReaderWriterLock();
            var readKey = rwl.ReaderLock();
            var cts     = new CancellationTokenSource();

            var writerLockReady = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
            var writerLockTask  = Task.Run(async() =>
            {
                var writeKeyTask = rwl.WriterLockAsync(cts.Token);
                writerLockReady.SetResult(null);
                await Assert.ThrowsAnyAsync <OperationCanceledException>(() => writeKeyTask);
            });
            await writerLockReady.Task;

            var readerLockReady = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
            var readerLockTask  = Task.Run(async() =>
            {
                var readKeyTask = rwl.ReaderLockAsync();
                readerLockReady.SetResult(null);
                await readKeyTask;
            });

            await readerLockReady.Task;

            cts.Cancel();

            await readerLockTask;
        }
Exemple #12
0
        /// <summary>
        /// check a request for rate limit
        /// </summary>
        /// <param name="request">a request</param>
        /// <returns>the stream of check result</returns>
        public AlgorithmCheckResult Check(object request)
        {
            if (_updatable)
            {
                using (var l = _mutex.ReaderLock())
                {
                    var originalRuleChecks = CheckAllRules(request);
                    var ruleCheckResults   = new List <RuleCheckResult>();
                    foreach (var result in originalRuleChecks)
                    {
                        ruleCheckResults.Add(result);
                    }

                    return(new AlgorithmCheckResult(ruleCheckResults));
                }
            }
            else
            {
                var originalRuleChecks = CheckAllRules(request);
                var ruleCheckResults   = new List <RuleCheckResult>();
                foreach (var result in originalRuleChecks)
                {
                    ruleCheckResults.Add(result);
                }

                return(new AlgorithmCheckResult(ruleCheckResults));
            }
        }
Exemple #13
0
 internal static bool ContainsWithLock <T>(this ICollection <T> collection, T item, AsyncReaderWriterLock rwLock)
 {
     using (rwLock.ReaderLock())
     {
         return(collection.Contains(item));
     }
 }
Exemple #14
0
 public Node <T> this[int index]
 {
     get
     {
         using (_rwLock.ReaderLock())
         {
             return(_steps[index]);
         }
     }
     set //TODO: to internal or remove
     {
         using (_rwLock.WriterLock())
         {
             _steps.Insert(index, value);
         }
     }
 }
Exemple #15
0
        protected IEnumerable <StreamingData <EXTRA> > Where(Func <StreamingData <EXTRA>, bool> subject)
        {
            IEnumerable <StreamingData <EXTRA> > result = null;

            try
            {
                using (locker.ReaderLock())
                {
                    result = this.streams.Where(subject).ToArray();
                }
            }
            catch (ApplicationException ex)
            {
                ErrorCode.LockFailedError.Throw(ex);
            }

            return(result);
        }
Exemple #16
0
 public TCell this[Node <T> a, Node <T> b]
 {
     get
     {
         using (_rwDataLock.ReaderLock())
         {
             return(_rawArray[_indexToNodeMap.IndexOf(a), _indexToNodeMap.IndexOf(b)]);
         }
     }
     set
     {
         _checkMap(a, b);
         using (_rwDataLock.WriterLock())
         {
             _rawArray[_indexToNodeMap.IndexOf(a), _indexToNodeMap.IndexOf(b)] = value;
         }
     }
 }
Exemple #17
0
        internal ConcurrentEnumerator(ICollection <T> collection, AsyncReaderWriterLock rwLock)
        {
            if ((collection == null) || (rwLock == null))
            {
                throw new ArgumentNullException(nameof(collection) + " || " + nameof(rwLock));
            }

            Lock       = rwLock.ReaderLock();
            Enumerator = collection.GetEnumerator();
        }
Exemple #18
0
 private bool Match(T item)
 {
     using (_lockFilters.ReaderLock())
     {
         if (_filters == null)
         {
             return(true);
         }
         return(item != null && _filters.Where(filter => filter.Expression != null).All(filter => filter.Expression(item)));
     }
 }
Exemple #19
0
 public static string HexiClientsToString(object addresses, AsyncReaderWriterLock locker)
 {
     if (addresses == null)
     {
         return("");
     }
     using (locker.ReaderLock())
     {
         var addr = (List <HexiUdpClient>)addresses;
         return(String.Join(", ", addr));
     }
 }
 bool IList.Contains(object value)
 {
     using (_lock.ReaderLock())
     {
         return(((IList)_list).Contains(value));
     }
 }
Exemple #21
0
 private void _checkMap(params Node <T>[] nodes)
 {
     using (_rwMapLock.ReaderLock())
     {
         foreach (var node in nodes)
         {
             if (!_indexToNodeMap.Contains(node))
             {
                 _indexToNodeMap.Add(node);
             }
         }
     }
 }
Exemple #22
0
        public IDisposable EnsureNotDisposed()
        {
            IDisposable disposable = null;

            try
            {
                disposable = _lock.ReaderLock(_cts.Token);
            }
            catch
            {
                // ignore
            }

            if (disposable == null ||
                _cts.IsCancellationRequested)
            {
                disposable?.Dispose();
                ThrowDisposed();
            }

            return(disposable);
        }
Exemple #23
0
        public void PurgeUnusedStreams()
        {
            var camsToKill = new List <int>();

            using (lck.ReaderLock())
            {
                foreach (int cameraId in processes.Keys)
                {
                    accessTimes.TryGetValue(cameraId, out DateTime lastAccessTime);
                    DateTime threshold = lastAccessTime.Add(oldStreamThreshold);

                    if (DateTime.Now > threshold)
                    {
                        camsToKill.Add(cameraId);
                    }
                }
            }

            if (camsToKill.Count > 0)
            {
                log.LogInformation("Purging {count} unused camera streams", camsToKill.Count);

                using (lck.WriterLock())
                {
                    foreach (int cameraId in camsToKill)
                    {
                        if (processes.TryGetValue(cameraId, out Process process))
                        {
                            log.LogDebug("Purging {cameraId} camera stream", cameraId);
                            process.Kill();
                        }

                        processes.Remove(cameraId);
                        accessTimes.Remove(cameraId, out _);
                    }
                }
            }
        }
Exemple #24
0
        public bool Get <TValue>(TKey key, out TValue value)
        {
            bool entryFound;

            using (var @lock = cacheLock.ReaderLock())
            {
                entryFound = cache.TryGetValue(key, out CacheEntry entry);
                if (entryFound && entry.Timestamp + TimeSpan.FromSeconds(CacheExpirationSeconds) > DateTime.Now)
                {
                    value = (TValue)entry.Value;
                    return(true);
                }
            };

            if (entryFound)
            {
                // cache expired
                using var wLock = cacheLock.WriterLock();
                cache.Remove(key);
            }

            value = default;
            return(false);
        }
Exemple #25
0
 public async static Task <int> ReadFirstItem()
 {
     using (await _lock.ReaderLock()) {
         return(_commonData.First());
     }
 }
 public IEnumerator <TItem> GetEnumerator() => new ConcurrentEnumerator <TItem>(Collection, Lock.ReaderLock());
Exemple #27
0
 public override void Reading(Action action)
 {
     AssertIsAlive();
     using (_sync.ReaderLock()) action();
 }
 public bool Contains(T item)
 {
     using (Lock.ReaderLock()) {
         return(HashSet.Contains(item));
     }
 }
Exemple #29
0
        protected override int?Execute(CommandExecutionToken <SQLiteCommand, SQLiteParameter> executionToken, CommandImplementation <SQLiteCommand> implementation, object state)
        {
            if (executionToken == null)
            {
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            }
            if (implementation == null)
            {
                throw new ArgumentNullException("implementation", "implementation is null.");
            }

            var mode = DisableLocks ? LockType.None : (executionToken as SQLiteCommandExecutionToken)?.LockType ?? LockType.Write;

            var startTime = DateTimeOffset.Now;

            OnExecutionStarted(executionToken, startTime, state);

            IDisposable lockToken = null;

            try
            {
                switch (mode)
                {
                case LockType.Read: lockToken = SyncLock.ReaderLock(); break;

                case LockType.Write: lockToken = SyncLock.WriterLock(); break;
                }

                using (var con = CreateConnection())
                {
                    using (var cmd = new SQLiteCommand())
                    {
                        cmd.Connection = con;
                        if (DefaultCommandTimeout.HasValue)
                        {
                            cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds;
                        }
                        cmd.CommandText = executionToken.CommandText;
                        //TODO: add potential check for this type.
                        cmd.CommandType = executionToken.CommandType;
                        foreach (var param in executionToken.Parameters)
                        {
                            cmd.Parameters.Add(param);
                        }

                        executionToken.ApplyCommandOverrides(cmd);

                        var rows = implementation(cmd);
                        executionToken.RaiseCommandExecuted(cmd, rows);
                        OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                        return(rows);
                    }
                }
            }
            catch (Exception ex)
            {
                OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                throw;
            }
            finally
            {
                if (lockToken != null)
                {
                    lockToken.Dispose();
                }
            }
        }
Exemple #30
0
 /// <summary>
 /// Access the machine model for read operations only
 /// </summary>
 /// <returns>Disposable lock object to be used with a using directive</returns>
 public static IDisposable AccessReadOnly()
 {
     return(new LockWrapper(_readWriteLock.ReaderLock(Program.CancellationToken), false));
 }