FreeRedis 实现源码
/// <summary>
/// 开启分布式锁,若超时返回null
/// </summary>
/// <param name="name">锁名称</param>
/// <param name="timeoutSeconds">超时(秒)</param>
/// <param name="autoDelay">自动延长锁超时时间,看门狗线程的超时时间为timeoutSeconds/2 , 在看门狗线程超时时间时自动延长锁的时间为timeoutSeconds。除非程序意外退出,否则永不超时。</param>
/// <returns></returns>
public LockController Lock(string name, int timeoutSeconds, bool autoDelay = true)
{name = $"RedisClientLock:{name}";var startTime = DateTime.Now;while (DateTime.Now.Subtract(startTime).TotalSeconds < timeoutSeconds){var value = Guid.NewGuid().ToString();if (SetNx(name, value, timeoutSeconds) == true){double refreshSeconds = (double)timeoutSeconds / 2.0;return new LockController(this, name, value, timeoutSeconds, refreshSeconds, autoDelay);}Thread.CurrentThread.Join(3);}return null;
}