Entity Framework 6.1.0 SaveChangesAsync

前端 未结 2 1934
挽巷
挽巷 2021-01-02 01:55

I have EF helper class that saves changes async:

public async Task SaveOrUpdateAsync(TEntity entity)
        where TEntity : class,         


        
相关标签:
2条回答
  • 2021-01-02 02:18

    perhaps I'm being stupid (!), but why does your code say

    if (dbEntry != null) dbEntry = entity;
    

    surely that if statement should be

    if (dbEntry == null) dbEntry = entity;
    

    I guess the C# null-coalescing operator would also work to replace both lines

    TEntity dbEntry = context.Set<TEntity>().Find(entity.Id) ?? entity;
    
    0 讨论(0)
  • 2021-01-02 02:21

    I figured it out!

    Here is the problem that was happening, when, you wait on the Task with the "Wait" method or take the result directly from the "Result" property of the Task, you block the main thread at the same time. When eventually the Task completes inside that method (SaveOrUpdateAsync(TEntity entity)) in the thread pool, it is going to invoke the continuation to post back to the main thread (as it never left it), because SynchronizationContext.Current is available and captured. But here is a problem: the main thread is blocked by "Wait" method and that is how I was getting a deadlock!

    To fix deadlock issue I had to specify to not to continue on captured context for context.SaveChangesAsync().

    public async Task<int> SaveOrUpdateAsync<TEntity>(TEntity entity)
            where TEntity : class, IContextEntity
        {
            if (entity.Id == 0)
                context.Set<TEntity>().Add(entity);
            else
            {
                TEntity dbEntry = context.Set<TEntity>().Find(entity.Id);
                if (dbEntry != null) dbEntry = entity;
            }
    
            return await context.SaveChangesAsync().ConfigureAwait(continueOnCapturedContext: false);
        }
    
    0 讨论(0)
提交回复
热议问题