Search code examples
c#sql-serversql-server-2008sql-server-2005sql-server-2016

how to detect sql server timeout from .NET application without using catch Exception


In my current application, i am performing an update by invoking T-SQL Update command. The problem is when the same record is locked by other users at that time.

At .NET application, the application will wait until SQL Server timeout, then it will throw the SqlException timeout.

Is it possible to perform a check first whether a particular record is locked by other process rather than catching the exception ?


Solution

  • No, not really.

    The standard way is to use try/catch and handle SqlException Number 1205 (deadlock victim), and retry your query:

        try
        {
            // do stuff...
        }
        catch (SqlException sqlEx)
        {
            switch (sqlEx.Number)
            {
                case -2:   // Client Timeout
                case 701:  // Out of Memory
                case 1204: // Lock Issue 
    
                case 1205: // >>> Deadlock Victim
                    // handle deadlock
                    break;
    
                case 1222: // Lock Request Timeout
                case 2627: // Primary Key Violation
                case 8645: // Timeout waiting for memory resource 
                case 8651: // Low memory condition 
                ...
            }
        }
    

    [Note: break statements not added for compactness

    Also note, many locking issues can be eliminated by providing the appropriate covering indexes.

    You can retrieve a complete list of SQL Server's error messages by querying sys.messages :

    SELECT * FROM sys.messages 
    WHERE language_id = 1033
    ORDER BY message_id