6

I have developed a Window Service using SQL Database currently in my DB is full of Record so query execuction taking much time while default command timeout is 30S but I want to increase it to 120S one option is

com.CommandTimeout = 120;

but I have many methods in my Application so I want to set it from APP.config file so it will be applicable for Application level, can anyone please tell me how could I achive this

Thanks

2
  • 4
    No such setting available that can be configure in app.config Commented Aug 14, 2014 at 7:09
  • Add a new command timeout setting under appSettings. Commented Aug 14, 2014 at 7:21

2 Answers 2

6

The easiest way to achieve this is to add a new entry in <appSettings> something like this:

<appSettings>
    <add key="commandTimeout" value="3000" />
</appSettings>

Afterwards, create a CommandFactory class that will populate the value

class CommandFactory
{
    public static int CommandTimeout
    {
        get
        {
            int commandTimeout = 0;
            var configValue = ConfigurationManager.AppSettings["commandTimeout"];
            if(int.TryParse(configValue, out commandTimeout))
               return commandTimeout;
            return 120; 
        }
    }

    public static SqlCommand CreateCommand(SqlConnection connection)
    {
        var command = new SqlCommand()
        {
            Connection = connection,
            CommandTimeout = CommandTimeout
        };
        return command;
    }
}

Now, in your code, instead of just instantiating a new SqlCommand just call the CommandFactory method:

using(var command = CommandFactory.CreateCommand(yourConnection))
{
    //
}
Sign up to request clarification or add additional context in comments.

Comments

-1

use this in app.config file

<configuration>
  <appSettings>
    <add key="connectioStringName" value="Data Source=source;Initial Catalog=tableName;User Id=databaseName;Password=password;Connection Timeout=3000"/>
  </appSettings>
</configuration>

1 Comment

This will set the ConnectionTimeout property of the SqlConnection not the command timeout. See MSDN msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.