Set custom default CommandTimeout for all new Command Objects

12,181

As far as I know no, there is no way to change this default. The constructor code for a SqlCommand is this:

public SqlCommand()
{
    this.ObjectID = Interlocked.Increment(ref _objectTypeCount);
    this._commandTimeout = 30;
    this._updatedRowSource = UpdateRowSource.Both;
    this._prepareHandle = -1;
    this._rowsAffected = -1;
    this._notificationAutoEnlist = true;
    GC.SuppressFinalize(this);
}

A possible workaround is to use a predefined SqlCommand passed as argument to the constructor that takes a SqlCommand as argument.

So you could create a global SqlCommand (a template)

 Dim commandTemplate60 = new SqlCommand()
 commandTemplate60.Timeout = 60

and then when you need a command with a timeout of 60 seconds

Dim cmd As New System.Data.SqlClient.SqlCommand(commandTemplate60)

However, setting directly the Timeout, doesn't seems to be a lot of work

Share:
12,181

Related videos on Youtube

KyleMit
Author by

KyleMit

I've been writing software for the last decade or so at StackOverflow, DealerPolicy, the Vermont Department of Health, code camps, meetups, and online. I'm primarily focused on web dev, react, dotnet, and azure, but always in the mood to debug something new. Favorite SO Accomplishments: 67k+ rep given away via bounties - currently 1st of all time twitter-bootstrap - 3rd person to get the Gold Badge Socratic - Asked a well-received question on 100 separate days Sportsmanship - Up vote 100 answers on questions where an answer of yours has a positive score Refiner - Edit and answer 50 questions

Updated on June 04, 2022

Comments

  • KyleMit
    KyleMit almost 2 years

    The default CommandTimeout value is 30 seconds. You can manually change the value on an instance of the command object by doing the following

    Dim cmd As New System.Data.SqlClient.SqlCommand
    cmd.CommandTimeout = 60
    

    Is there a way to specify a different default value, such that all new command objects will automatically have this value within your solution when they are created?

  • Kiquenet
    Kiquenet over 5 years
    Not constant value for default value ._commandTimeout = 30; ?