gpt4 book ai didi

c# - 锁定异步任务c#

转载 作者:行者123 更新时间:2023-12-02 03:33:56 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com