public IDisposable LockSeed(TimeSpan timeout) { if (!_sema.Wait(timeout)) { SimpleLockItem.TimeoutError(Convert.ToString(this.Key), timeout); } return(_releaseItem); }
public async Threading.Tasks.Task <IDisposable> LockSeedAsync(TimeSpan timeout) { if (!await _sema.WaitAsync(timeout)) { SimpleLockItem.TimeoutError(Convert.ToString(this.Key), timeout); } return(_releaseItem); }
/// <summary> /// 实现一个 Redis 锁的功能。 /// </summary> /// <param name="client">Redis 客户端。</param> /// <param name="key">锁的键名。</param> /// <param name="timeout">锁的超时设定。</param> /// <returns>释放时解除占用的锁。</returns> /// <exception cref="System.TimeoutException">获取锁超时。</exception> public static IDisposable Lock(this IRedisClient client, string key, TimeSpan?timeout = null) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } var realSpan = timeout ?? DefaultLockTimeout; if (!SpinWait.SpinUntil(() => client.HSet(LockKey, key, 1, nx: true), realSpan)) { SimpleLockItem.TimeoutError(key, realSpan); } return(new SimpleLockItem(() => client.HDel(LockKey, key))); }
public Seed(object key) { Key = key; _sema = new SemaphoreSlim(1, 1); _releaseItem = new SimpleLockItem(() => _sema.Release()); }