1

DbContext への変更を保存するコストを支払う前に、クライアントに応答を返したいと思います。応答を返した後に変更を保存できますか? コンテキストが破棄されるため、単純に ThreadPool.QueueUserWorkItem にスローすると失敗します。

ありがとう!

4

1 に答える 1

2

この場合、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;
}
于 2013-03-07T20:39:17.567 に答える