public async void should_lock_resource()
        {
            var lockId = Guid.NewGuid().ToString();

            await _subject.Start();

            var first = await _subject.AcquireLock(lockId);

            var second = await _subject.AcquireLock(lockId);

            await _subject.Stop();

            Assert.True(first);
            Assert.False(second);
        }
        public TResult Get <TResult>(string key, Func <AcquireContext <string>, TResult> acquire, Func <TResult> fallback, TimeSpan timeout)
        {
            // When using with arbitrary types, key.ToString() could lead to errors if the key is not string or the ToString() is not properly implemented.
            // That's why we only allow string keys here.

            try
            {
                return(_cacheManager.Get(key, ctx =>
                {
                    using (var lockFile = _lockManager.AcquireLock(key, timeout))
                    {
                        // If we waited for the lock to be released, here the result computed by the locking code should be returned.
                        return _cacheManager.Get(key, acquire);
                    }
                }));
            }
            catch (TimeoutException)
            {
                return(fallback());
            }
        }
예제 #3
0
 /// <summary>
 /// Tries to acquire a lock with the specified parameters
 /// </summary>
 /// <param name="name">Unique name of the lock</param>
 /// <returns>The ILockFile instance on success.</returns>
 /// <exception cref="System.TimeoutException">Thrown if the lock couldn't be acquired.</exception>
 public static IDistributedLock AcquireLock(this IDistributedLockManager lockFileManager, string name)
 {
     return(lockFileManager.AcquireLock(name, new TimeSpan(0, 0, 0, 4)));
 }