【发布时间】:2015-11-04 21:06:02
【问题描述】:
我有多个控制台应用程序,但它们会读取和插入更新同一个 sql 表。我使用了 transactionscope,但我收到了这个错误 “事务(进程 ID)在锁定资源上与另一个进程死锁,并已被选为死锁受害者。重新运行事务。”
我的 catch 块中出现异常。我怎样才能避免这种情况? 我知道问题是什么,但我不确定应该是什么可能的解决方案。我在不同的论坛上看到了很多问题,但没有一个对我有真正的帮助。
我的代码中的一切都好吗?
bool isMaster = false;
tourneyInstanceTrackerId = 0;
using (JG_RummyEntities dbContext = new JG_RummyEntities())
{
try
{
using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required,new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead }))
{
bool isAnyMaster = dbContext.TourneyInstanceTrackers.Any(t => t.IsMaster & t.TournamentId == tournamentId);
TourneyInstanceTracker tourneyInstanceTracker = new TourneyInstanceTracker
{
TournamentId = tournamentId,
IsMaster = !isAnyMaster,
CreateDate = DateTime.Now
};
dbContext.AddToTourneyInstanceTrackers(tourneyInstanceTracker);
dbContext.SaveChanges();
var result = dbContext.TourneyInstanceTrackers.Where(t => t.TournamentId == tournamentId)
.OrderByDescending(t => t.CreateDate)
.Select(t => new { t.IsMaster, t.Id })
.FirstOrDefault();
if (result != null)
{
isMaster = result.IsMaster;
tourneyInstanceTrackerId = result.Id;
}
transaction.Complete();
}
}
catch (Exception ex)
{
Logger.Log("Got exception in SetTournamentInTourneyInstanceTracker : " + ex.Message + ", " + ex.StackTrace + ", "+ tournamentId);
}
}
【问题讨论】:
标签: c# sql entity-framework objectcontext