Patterns for handling a SQL deadlock in C#?

后端 未结 2 1466
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 06:49

I\'m writing an application in C# which accesses a SQL Server 2005 database. The application is quite database intensive, and even if I try to optimize all access, set up proper

相关标签:
2条回答
  • 2021-02-19 07:25

    I posted a code sample to handle exactly this a while back, but SO seemed to lose my account in the interim so I can't find it now I'm afraid and don't have the code I used here.

    Short answer - wrap the thing in a try..catch. If you catch an error which looks like a deadlock, sleep for a short random time and increment a retry the counter. If you get another error or the retry counter clears your threshold, throw the error back up to the calling routine.

    (And if you can, try to bung this in a general routine and run most/all of your DB access through it so you're handling deadlocks program-wide.)

    EDIT: Ah, teach me not to use Google! The previous code sample I and others gave is at How to get efficient Sql Server deadlock handling in C# with ADO?

    0 讨论(0)
  • 2021-02-19 07:46

    Here is the approach we took in the last application framework I worked on. When we detected a deadlock, we simply reran the transaction. We did this up to 5 times. If after 5 times it failed, we would throw an exception. I don't recall a time that the second attempt ever failed. We would know because we were logging all activity in the backend code. So we knew any time a deadlock occurred, and we knew if it failed more than 5 times. This approach worked well for us.

    Randy

    0 讨论(0)
提交回复
热议问题