94

I am trying to override the default SqlConnection timeout of 15 seconds and am getting an error saying that the

property or indexer cannot be assigned because it is read only.

Is there a way around this?

using (SqlConnection connection = new SqlConnection(Database.EstimatorConnection))
{
   connection.Open();

   using (SqlCommand command = connection.CreateCommand())
   {
       command.CommandType = CommandType.StoredProcedure;
       connection.ConnectionTimeout = 180; // This is not working 
       command.CommandText = "sproc_StoreData";
       command.Parameters.AddWithValue("@TaskPlanID", order.Projects[0].TaskPlanID);
       command.Parameters.AddWithValue("@AsOfDate", order.IncurDate);

       command.ExecuteNonQuery();
    }
}
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Haymak3r
  • 1,321
  • 1
  • 11
  • 17
  • 5
    Do you mean to set a connection timeout after you try to open the connection? do you mean commandtimeout? – Alex K. Apr 11 '12 at 15:01
  • 2
    I really, really don't see why they made the property read-only. Shoulda been read-write, IMO. – xofz May 11 '16 at 20:15
  • 1
    The property is read-only after connection. See other responses for discussion. ConnectionTimeout impacts timeout when attempting to connect. it's often useful to increase this for Azure SQL DB. CommandTimeout impacts timeout when running a query. – Bill Gibson - MSFT Jul 31 '17 at 17:40
  • 1
    @Sam Pearson It is read-write right up until the connection is opened i.e. when connection.Open(); is called. From this point the timer is already running. – WonderWorker Aug 30 '17 at 15:18

10 Answers10

185

If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.

Its usage is:

command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.
Anil Mathew
  • 2,590
  • 1
  • 15
  • 15
45

You can set the timeout value in the connection string, but after you've connected it's read-only. You can read more at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

As Anil implies, ConnectionTimeout may not be what you need; it controls how long the ADO driver will wait when establishing a new connection. Your usage seems to indicate a need to wait longer than normal for a particular SQL query to execute, and in that case Anil is exactly right; use CommandTimeout (which is R/W) to change the expected completion time for an individual SqlCommand.

KeithS
  • 70,210
  • 21
  • 112
  • 164
24

A cleaner way is to set connectionString in xml file, for example Web.Confing(WepApplication) or App.Config(StandAloneApplication).

 <connectionStrings>
    <remove name="myConn"/>
    <add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>
  </connectionStrings>

By code you can get connection in this way:

public static SqlConnection getConnection()
{
        string conn = string.Empty;
        conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
        SqlConnection aConnection = new SqlConnection(conn);
        return aConnection;
}

You can set ConnectionTimeout only you create a instance. When instance is create you don't change this value.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
daniele3004
  • 13,072
  • 12
  • 67
  • 75
17

You could always add it to your Connection String:

connect timeout=180;
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 5
    Connection Timeout is different from CommandTimeout. Connection Timeout is for the amount of time it takes to resolve the initial connection to the database. CommandTimeout changes the timeout period for the particular query. – m0g Apr 04 '14 at 13:32
  • @m0g I don't understand why this isn't the accepted answer. The question here probably is very clearly about the Connection Timeout, which defaults to 15, and is a read-only property of an SqlConnection that must be defined in the Connection String. The line of code the poster lists specifically tries to set SqlConnection.ConnectionTimeout. The Command Timeout defaults to 30, and is a read/write parameter of the SqlCommand, a completely different object. The question's error message shows a value of 15, and the question specifically says SqlConnection, not SqlCommand. – Bacon Bits Nov 08 '18 at 21:18
  • 3
    @BaconBits what the question poster described and asked versus what he wants is different therefore the accepted answer is something different. – m0g Nov 14 '18 at 20:59
13

You can also use the SqlConnectionStringBuilder

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 10;
using (var connection = new SqlConnection(builder.ToString()))
{
    // code goes here
}
Kelvin
  • 206
  • 3
  • 4
9

You can add Connection Timeout=180; to your connection string

Horev Ivan
  • 270
  • 3
  • 9
  • 5
    Connection Timeout is different from CommandTimeout. Connection Timeout is for the amount of time it takes to resolve the initial connection to the database. CommandTimeout changes the timeout period for the particular query. – m0g Apr 04 '14 at 13:37
6

Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.

As others have said:

connection.ConnectionTimeout is used for the initial connection

command.CommandTimeout is used for individual searches, updates, etc.

But:

connection.ConnectionTimeout is also used for committing and rolling back transactions.

Yes, this is an absolutely insane design decision.

So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.

Nick Thompson
  • 73
  • 1
  • 5
  • "Connection.ConnectionTimeout is also used for committing and rolling back transactions. Yes, this is an absolutely insane design decision." Really? I don't believe this is true. If it was true, then any transaction that lasts longer than the connection timeout of 15 seconds would fail. You need to clarify. – Triynko May 09 '19 at 18:30
  • Now, if you mean it used as the timeout for submitting just the commit or rollback command by itself, then no... that's not an insane decision. It's basically an instantaneous command that should return immediately, since it's just signaling the server to commit or roll back. If it fails to reach the server and get a response back immediately, then that's basically a connection timeout, which is why it would make sense to use that way. – Triynko May 09 '19 at 18:32
6

You can set the connection timeout to the connection level and command level.

Add "Connection Timeout=10" to the connection string. Now connection timeout is 10 seconds.

var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;Connection Timeout=10";
using (var con = new SqlConnection(connectionString))
{

}

Set the of CommandTimeout property to SqlCommand

var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword";
using (var con = new SqlConnection(connectionString))
{

    using (var cmd =new SqlCommand())
    {
        cmd.CommandTimeout = 10;
    }

}
Jakir Hossain
  • 91
  • 1
  • 7
  • I think your answer is the cleanest. My application is through CLI, and I like adding to the connection string. Thanks. – Mark Longmire Mar 16 '21 at 17:18
3

I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/

Basically, you either set Connect Timeout in the connection string like this:

Data Source=server;Initial Catalog=databaseUser Id=username;Password=password;Connect Timeout=30

Or you set ConnectionTimeout on the command object like this:

sqlCommand.CommandTimeout = 30;

Be aware that the timeout time is in seconds.

Furthermore, this timeout does not account for loss of connection because of situation like a dead or overloaded server. Those would eventually trigger a TCP timeout. See the blogpost for a nice extension example to handle that too.

macnerd
  • 181
  • 1
  • 6
  • Hello and welcome to SO! Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) Adding code samples is always helpful. – Tomer Shetah Dec 17 '20 at 13:14
  • Avoid using links only, the links could change in the future. Add some valuable tips and some source code to help clarify your answer if necessary – ColinWa Dec 17 '20 at 13:15
2

You need to use command.CommandTimeout

Luke
  • 11,426
  • 43
  • 60
  • 69
LewisT
  • 74
  • 2