如何在同时运行这两个语句时阻止EntityFramework死锁

Phi*_*ght 9 c# deadlock entity-framework

调用我的Web服务使用以下代码以确保调用者具有有效的会话.如果找到有效会话,则会更新会话详细信息并保存更改.一切都很简单,工作正常.

// Create the Entity Framework context
using(MyContext ctx = CreateMyContext())
{
     // Get the user session for the client session         
     UserSession session = (from us in context.UserSessions.Include("UserEntity")
                            where us.SessionId = callerSessionId
                            select us).FirstOrDefault<UserSession>();

     if (session == null)
         return false;
     else
     {
         // Update session details
         session.Calls++;
         session.LastAccessed = DateTime.Now.Ticks;
         Console.WriteLine("Call by User:{0}", session.UserEntity.Name);

         // Save session changes back to the server
         ctx.SaveChanges();
         return true;
     }    
}
Run Code Online (Sandbox Code Playgroud)

一切正常,直到相同的调用者,因此相同的会话,进行多个并发调用(这是完全有效的).在这种情况下,我有时会遇到僵局.使用SQL Server Profiler我可以看到发生以下情况.

呼叫者A执行选择并获取用户会话上的共享锁.呼叫者B执行选择并在同一用户会话上获取共享锁.由于来电者B的共享锁定,来电者A无法执行更新.由于呼叫者A的共享锁,呼叫者B无法执行其更新.僵局.

这似乎是一个简单而经典的死锁场景,必须有一个简单的方法来解决它.当然,几乎所有真实世界的应用程序都有同样的问题.但是我没有提到任何有关死锁的实体框架书籍.

Jar*_*red 12

我发现了一篇关于这里的文章.它基本上听起来像你可以启动和停止围绕你的EF调用的交易...该块提供以下代码示例,所以信用转到Diego B Vega ...博客文章还链接到另一个博客和其他信息.

using (var scope = new TransactionScope(TransactionScopeOption.Required, new 
    TransactionOptions { IsolationLevel= IsolationLevel.Snapshot }))
{
    // do something with EF here
    scope.Complete();
}
Run Code Online (Sandbox Code Playgroud)