【问题标题】:Chosen as the deadlock victim on simple Add() -> SaveChanges()在简单的 Add() -> SaveChanges() 上被选为死锁受害者
【发布时间】:2018-09-11 12:32:53
【问题描述】:

这个简单的程序

private static void Main(string[] args)
{
    Parallel.For(0, 1000000, InsertTestEntity);
}

private static void InsertTestEntity(int i)
{
    using (var dbContext = new TestDbContext())
    {
        dbContext.TestEntities.Add(new TestEntity { HugeString = "Baby shark," + string.Join(", ", Enumerable.Repeat("doo", 500)) });
        dbContext.SaveChanges();
    }
}

public class TestEntity
{
    [Key]
    public int Id { get; set; }

    public string HugeString { get; set; }
}

public class TestDbContext : DbContext
{
    public DbSet<TestEntity> TestEntities { get; set; }
}

抛出类似的异常

System.Data.Entity.Infrastructure.DbUpdateException
  HResult=0x80131501
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at EntityFrameworkStressTest.Program.InsertTestEntity(Int32 i) in c:\Git\EntityFrameworkStressTest\EntityFrameworkStressTest\Program.cs:line 18
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()

Inner Exception 1:
UpdateException: An error occurred while updating the entries. See the inner exception for details.

Inner Exception 2:
SqlException: Transaction (Process ID 100) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

SSMS 中的 SQL 表如下所示

【问题讨论】:

标签: c# sql-server entity-framework ssms


【解决方案1】:

如 SSMS 屏幕截图所示,似乎没有主键指示。 ID 列旁边应该有一个钥匙符号。

进一步检查发现 Id 确实被声明为身份(AUTO INCREMENT 的 SQL Server),但不是主键。要使Id 成为真正的主键,请右键单击SSMS 中的表并选择设计,右键单击列设计器中的Id 行并单击SET PRIMARY KEY:

在此之后,压力测试运行而不会自行死锁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多