What is good C# coding style for catching SQLException and retrying

后端 未结 8 661
慢半拍i
慢半拍i 2020-12-05 02:55

I have a method that calls a SQLServer function to perform a free text search against a table. That function will occasionally on the first call result in a SQLException: \"

相关标签:
8条回答
  • 2020-12-05 03:57

    I'd change the exception handling to only retry on certain errors:

    • 1204, 1205 deadlocks
    • -2 timeout
    • -1 connection broken

    These are the basic "retryable" errors

    catch (SqlException ex)
    {
        if !(ex.Number == 1205 || ex.Number == 1204 || ... )
        {
            throw
        }
        retryCount++;
        if (retryCount > MAX_RETRY) throw;
    }
    

    Edit, I clean forgot about waits so you don't hammer the SQL box:

    • Add a 500 ms wait on deadlock
    • Add a 5 sec delay on timeout

    Edit 2:

    I'm a Developer DBA, don't do much C#. My answer was to correct exception processing for the calls...

    0 讨论(0)
  • 2020-12-05 04:00

    Pull the relevant code out into its own method, then use recursion.

    Pseudo-code:

    try
    {
        doDatabaseCall();
    }
    catch (exception e)
    {
        //Check exception object to confirm its the error you've been experiencing as opposed to the server being offline.
        doDatabaseCall();
    }
    
    0 讨论(0)
提交回复
热议问题