【问题标题】:Async DbContext.SaveChanges EF 5, savechanges after returning a response (MVC/WebAPI)Async DbContext.SaveChanges EF 5,返回响应后保存更改(MVC/WebAPI)
【发布时间】:2013-03-07 20:02:02
【问题描述】:

我想在支付保存对 DbContext 更改的成本之前将响应返回给客户端。我可以在返回响应后保存更改吗?由于上下文已被释放,因此只需将其放入 ThreadPool.QueueUserWorkItem 就会失败。

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-web-api


    【解决方案1】:

    在这种情况下,您处理 DbContext 的逻辑过于复杂,无法使用 using 块;您需要手动处理。您的代码可能看起来更像:

    DbContext context = null;
    try
    {
        context = new DbContext();
        var query = context.GetStuff();
    
        ThreadPool.QueueUserWorkItem(_ =>
        {
            try
            {
                context.SaveChanges();
            }
            finally
            {
                context.Dispose();
            }
        });
    }
    catch
    {
        //dispose of the context only if there was an exception, as it 
        //meant we weren't able to get into the async task and dispose of it there
        if (context != null)
            context.Dispose();
    
        throw;
    }
    

    【讨论】:

    • 我正在使用由控制器构造的 DbContext,但您的观点完全正确。我的解决方法是挂起 dispose 方法,直到提交完成。让我想知道是否将 QueueCommit 字段添加到上下文中,然后在 Dispose { if (QueueCommit) SaveChanges(); } 是个好主意(当然是 try/finally)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多