我正在尝试来自DistributedLock nuget的分布式锁。
这是我使用的代码片段:
class Program
{
private static SqlConnection _sqlConn = new SqlConnection("my connection string");
static void Main(string[] args)
{
int pid;
using (var p = Process.GetCurrentProcess()) { pid = p.Id; }
TestSqlLocking(pid).Wait();
}
private static async Task TestSqlLocking(int processId)
{
_sqlConn.Open();
var t1 = DoWorkAsyncWithSqlLock($"Process {processId} Client 1");
var t2 = DoWorkAsyncWithSqlLock($"Process {processId} Client 2");
var t3 = DoWorkAsyncWithSqlLock($"Process {processId} Client 3");
var t4 = DoWorkAsyncWithSqlLock($"Process {processId} Client 4");
await Task.WhenAll(t1, t2, t3, t4);
}
private static async Task DoWorkAsyncWithSqlLock(string client)
{
var sqlDistributedLock = new SqlDistributedLock("myLock", _sqlConn);
Console.WriteLine($"SQL Before taking the lock for client [{client}]");
await using (await sqlDistributedLock.AcquireAsync(TimeSpan.FromSeconds(10)))
{
Console.WriteLine($"SQL After taking the lock and doing some work for client [{client}]");
await Task.Delay(1000);
Console.WriteLine($"SQL After doing some work and releasing lock for client [{client}]");
}
}
}
问题是我总是在第一次获取锁后超时,就好像它永远不会被释放一样。虽然据说锁在处理后会被释放。但这并没有发生。第二个任务永远无法进入锁。
我得到的输出是:
SQL Before taking the lock for client [Process 8864 Client 1]
SQL Before taking the lock for client [Process 8864 Client 2]
SQL Before taking the lock for client [Process 8864 Client 3]
SQL Before taking the lock for client [Process 8864 Client 4]
SQL After taking the lock and doing some work for client [Process 8864 Client 1]
SQL After doing some work and releasing lock for client [Process 8864 Client 1]
然后我得到超时。