Charles Xavier
Charles Xavier

Reputation: 1045

Timeout expired when running an SP more than 30 seconds

I have an sp that runs for 45 sec- 1 min but it gives me the error message Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. I have add the Connect Timeout=120 to the connection string but that didnt help. I've also change the IIS application pool to timeout after 2 mins.

<add name="Oconnection" connectionString="Data Source=servername;Initial Catalog=dmName; User ID=username; Password=pw; Connect Timeout=120" />

This is my cs file:

  string Oconnection=ConfigurationManager.ConnectionStrings["Oconnection"].ConnectionString;



 public DataSet CreateTable()
    {
        DataSet dsCreateTable;
        dsCreateTable = SqlHelper.ExecuteDataset(Oconnection, CommandType.StoredProcedure, "usp_CreateTables");
        return dsCreateTable;
    }

Do I need to add the timeout in the cs file as well?

Upvotes: 5

Views: 8300

Answers (1)

mortb
mortb

Reputation: 9849

Connect Timeout is the time limit for connecting to the sql server.

What you want is CommandTimeout which is the timeout for running a command (query, stored procedure etc)

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.commandtimeout?view=netframework-4.7.2

You need to set the CommandTimeout proptery on the SqlCommand object, it is not possible to set in connection string.

You can use it in your code like this:

public DataSet CreateTable()
{
    using(var conn = new SqlConnection(Oconnection))
    {
       conn.Open();
       using(var command = new SqlCommand())
       {
          command.Connection = conn;
          command.CommandTimeout = 120; // higher if needed
          command.CommandType = CommandType.StoredProcedure;
          command.CommandText = "usp_CreateTables";
          var da = new SqlDataAdapter();
          da.SelectCommand = command;
          var ds = new DataSet();
          da.Fill(ds);

          return ds;
      }
   }
}

Upvotes: 10

Related Questions