Ejemplo n.º 1
0
        /// <summary>
        /// Creates a new <see cref="AccessLock"/>. The lock may or may not be acquired.
        /// </summary>
        /// <param name="semaphore">The underlying semaphore that synchronizes access to objects.</param>
        /// <param name="timeout">
        /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait to acquire an access lock,
        /// a <see cref="TimeSpan"/> that represents -1 milliseconds to wait indefinitely,
        /// or a <see cref="TimeSpan"/> that represents 0 milliseconds to test the semaphore and return immediately.
        /// </param>
        /// <returns>A new <see cref="AccessLock"/>.</returns>
        public static AccessLock TryCreate(SemaphoreSlim semaphore, TimeSpan timeout)
        {
            var accessLock = new AccessLock(semaphore);

            accessLock.AcquireLock(timeout);
            return(accessLock);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets a new access lock for the specified key.
        /// The lock is guaranteed to be acquired. Or an exception is thrown.
        /// </summary>
        /// <param name="key">The key to get access lock for.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> that represents the time period to wait to acquire access locks.</param>
        /// <returns>A new access lock for the specified key.</returns>
        public AccessLock GetLock(TKey key, TimeSpan?timeout = default)
        {
            var semaphore = this.semaphores.GetOrAdd(key, _ => new SemaphoreSlim(this.maxCount, this.maxCount));

            return(AccessLock.Create(semaphore, timeout ?? this.timeout));
        }