public class MyDbContext : DbContext
{
....
static readonly object lockObject = new object();
public override int SaveChanges()
{
lock (lockObject)
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
lock (lockObject)
return base.SaveChangesAsync(cancellationToken);
}
}
我想在多个线程中使用DbContext,但是如果两个线程同时写入,底层数据库就会出现问题。 所以我使用lockObject来防止同时发生两个SaveChanges()。
这在 SaveChanges() 中工作得很好,但我不知道如何在 SaveChangesAsync() 中执行相同的操作。 我认为上面的解决方案是错误的。 如何将锁应用于 SaveChangesAsync?
谢谢!
最佳答案
来自https://blog.cdemi.io/async-waiting-inside-c-sharp-locks/ 你可以使用:
public class MyDbContext
{
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
public override int SaveChanges()
{
semaphoreSlim.Wait();
try
{
return base.SaveChanges();
}
finally
{
//When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
//This is why it is important to do the Release within a try...finally clause; program execution may crash or take a different path, this way you are guaranteed execution
semaphoreSlim.Release();
}
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
await semaphoreSlim.WaitAsync(cancellationToken);
try
{
return await base.SaveChangesAsync();
}
finally
{
//When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
//This is why it is important to do the Release within a try...finally clause; program execution may crash or take a different path, this way you are guaranteed execution
semaphoreSlim.Release();
}
}
}
关于c# - 锁定异步任务c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602757/