简体   繁体   中英

Is it safe to override SaveChanges and SaveChangesAsync like this?

I have some custom logic that is performed around the SaveChangesAsync method. The problem is that I have some legacy code that calls SaveChanges instead. I have determined that the code below could be fine, but I'm afraid of any possible side-effect (deadlocks). I have had problems trying to turn asynchronous calls into synchronous calls.

class SomeDbContext : DbContext
{
    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
    {
        BeforeSaveChanges();
        var result = await base.SaveChangesAsync(cancellationToken);
        await DispatchDomainEvents();
        return result;
    }

    public override int SaveChanges()
    {
        return SaveChangesAsync().GetAwaiter().GetResult();
    }
}

You should copy the same implemenetation in the sync SaveChanges method:

class SomeDbContext : DbContext
{
    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
    {
        BeforeSaveChanges();
        var result = await base.SaveChangesAsync(cancellationToken);
        await DispatchDomainEvents();
        return result;
    }

    public override int SaveChanges()
    {
        BeforeSaveChanges();
        var result = base.SaveChanges();
        DispatchDomainEvents().Wait(); // Ideally, you should have a sync version for this method too
        return result;
    }
}

Blocking the current thread to wait for an async method to finish may lead to thread starvation in some scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM