c# - 锁定异步任务c#

标签 c# asynchronous locking

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/

相关文章:

python - 用户启动的后台进程数量有限

c - pthread_mutex_trylock 段错误

c# - Rhino Mocks - stub 一个单例

c# - 用户控件上的按钮监听器

php - 发送 Guzzle 的 "async"请求而不调用 "wait"

f# - 任务并行库与异步工作流

command-line - 手动停止构建时 Gradle .lock 文件未删除

go - 返回 channel 的并发队列,锁定疑惑

c# - .NET 字典作为属性

c# - Prism 5 Wpf - 登录窗口显示两次