susparsy
susparsy

Reputation: 1046

Set time limit for DB query

I want to set a time limit for a certain db query.

How do I do that?

try
{
    using (SqlConnection connection = new SqlConnection(ConString)
    {
        using (SqlCommand command = new SqlCommand())
        {
            command.CommandText = sp;

            command.CommandType = CommandType.StoredProcedure;

            command.Connection = connection;

            command.Connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                string role = "";
                if (reader.Read())
                    role = reader.GetString(0);

                reader.Close();
            }
        }
    }
}
catch (Exception ex)
{
     //throw new Exception(string.Format("DBLayer failure in {0}: {1}", sp, ex.Message), ex);
}

Upvotes: 0

Views: 452

Answers (1)

Ian Nelson
Ian Nelson

Reputation: 58753

You set the CommandTimeout property on your SqlCommand object to your desired time limit (in seconds).

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx

Upvotes: 4

Related Questions