I want to use Redis for distributed lock. I'm using RedLock.net nuget package for this. But thread is able to acquire the lock, even another thread is already acquired the lock.
Here is sample code:
public void Demo(RedLockFactory redLockFactory)
{
Parallel.For(0, 5, x =>
{
TimeSpan expiry = TimeSpan.FromSeconds(30);
var wait = TimeSpan.FromSeconds(10);
var retry = TimeSpan.FromSeconds(1);
string user = $"User:{x}";
using (var redLock = redLockFactory.CreateLock(resource, expiry, wait, retry))
{
// make sure we got the lock
if (redLock.IsAcquired)
{
Console.WriteLine($"{user} acquired lock at {DateTimeOffset.Now.ToString("dd-MM-yyyy HH:mm:ss")}.");
}
else
{
Console.WriteLine($"{user} didn't get the lock.");
}
}
});
}
This is output of my demo
User:4 acquired lock at 06-10-2020 09:24:34.
User:2 acquired lock at 06-10-2020 09:24:34.
User:1 acquired lock at 06-10-2020 09:24:34.
User:0 acquired lock at 06-10-2020 09:24:35.
User:3 acquired lock at 06-10-2020 09:24:35.
As you can see, every thread is able to acquire the lock, which should not happen.
Once lock is acquired then other thread should not able to acquire the lock.