Set custom default CommandTimeout for all new Command Objects

佐手、 提交于 2019-12-10 12:31:13

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/18089812/set-custom-default-commandtimeout-for-all-new-command-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!