How to get efficient Sql Server deadlock handling in C# with ADO?

前端 未结 4 1538
旧巷少年郎
旧巷少年郎 2020-12-02 09:54

I have a class \'Database\' that works as a wrapper for ADO.net. For instance, when I need to execute a procedure, I call Database.ExecuteProcedure(procedureName, parameters

4条回答
  •  隐瞒了意图╮
    2020-12-02 10:55

    If the deadlock can be solved at the data layer, that's definitely the way to go. Locking hints, redesigning the way the module works and so on. NoLock isn't a panacea though - sometimes it's not possible to use for reasons of transactional integrity and I have had cases of straight (albeit complex) data reads with all relevant tables NoLock'd that still caused blocks on other queries.

    Anyway - if you can't solve it at the data layer for whatever reason, how about

    bool OK = false;
    Random Rnd = new Random();
    
    while(!OK)
    {
        try
        {
            rows = Command.ExecuteNonQuery();
            OK = true;
        }
        catch(Exception exDead)
        {
            if(exDead.Message.ToLower().Contains("deadlock"))
                System.Threading.Thread.Sleep(Rnd.Next(1000, 5000));
            else
                throw exDead;
        }
    }
    

提交回复
热议问题