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

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


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 could use separate connection with very short timeout to attempt to lock the record by updating some field, but this is still not going to give you 100% reliability.

if you really have the situation with multiple users editing same records, you should look into optimistic locking techniques.

Also, make sure you do not allow users to lock the records at all - use disconnected mode for any updates. In other words, the locking will only occur for a short time of update (<100 ms)