小编Gab*_*zer的帖子

为什么我的线程陷入Entity Framework SaveChangesAsync?

我们遇到了Entity Framework的一个奇怪问题.我们正在尝试向数据库添加一个新对象,并且正在从几个不同的位置执行此操作.两者都使用通过nuget包加载的以下代码:

public async Task<Guid> AddRecurrenceHistoryAsync(RecurrenceHistory recurrenceHistory, Guid recurrenceId)
{
    _logger.DebugLogInformation("+");

    try
    {
        using (RecurringPaymentsContext context = new RecurringPaymentsContext())
        {
            var recur = context.RecurringPayments.Single(r => r.Id == recurrenceId);
            if (recur.RecurrenceHistories == null)
            {
                _logger.DebugLogInformation($"No existing histories found");
                recur.RecurrenceHistories = new List<RecurrenceHistory>();
            }
            recur.RecurrenceHistories.Add(recurrenceHistory);
            _logger.DebugLogInformation($"Saving Changes");
            var result = await context.SaveChangesAsync();
            _logger.DebugLogInformation($"Changes Saved result: {result}");
        }
    }
    catch (Exception e)
    {
        _logger.DebugLogError(e.ToString());
        throw;
    }

    _logger.DebugLogInformation(string.Format("- return: {0}", recurrenceHistory.Id));
    return recurrenceHistory.Id;
}
Run Code Online (Sandbox Code Playgroud)

从我们的控制台应用程序中执行此操作非常有效,但是我们也尝试从WebApi服务端点(下面给出的简化测试代码)执行此操作,并且从那里调用它时代码卡var result = await context.SaveChangesAsync();在线上.

Web服务测试端点:

[HttpGet]
[Route("test")] …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading entity-framework asp.net-web-api

2
推荐指数
1
解决办法
567
查看次数