0

I'm trying to raise a timeout error in my SQL Server query using c#. I thought a timer would work; however I'm new to c# and have been having trouble figuring it out. I've searched through several questions on this site, and on other sites trying to find out how to raise a timeout error of my query.

Here is my code:

using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                cmd.CommandTimeout = timeOut;
                cmd.Connection = DBAction.GetSqlConnection(projectId);
                SqlDataReader reader = cmd.ExecuteReader();
                
                    string[] colname = Enumerable.Range(0, reader.FieldCount).Select(x => reader.GetName(x)).ToArray();
                    while (reader.Read())
                            {
                                 //do something
                            }       
            }

I'm not sure on how to add a timer to this that returns an error when the execution of the query takes longer than the specified time, or even where to put it. I've tried finding other posts about it but none of the ones I've found are similar to this; I could also just be really bad at my searches. Any kind of help would be appreciated, and if you need any more information let me know. I renamed a few things for security, but this is how the code is otherwise. To note: I'm using this for testing purposes, and not for production, so only a few people will ever actually see this but it's necessary.

Nirusma
  • 13
  • 4
  • Does this answer your question? [Cancel execution of command if it takes too long](https://stackoverflow.com/questions/34764279/cancel-execution-of-command-if-it-takes-too-long) – gunr2171 Jan 26 '21 at 15:58
  • 3
    If you are running a SQL statement, and want it to timeout, then you set a timeout value in against the `Sqlcommand` or `SqlConnection`. See [SqlCommand.CommandTimeout Property](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.commandtimeout?view=dotnet-plat-ext-5.0) and [SqlConnection.ConnectionTimeout Property](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectiontimeout?view=dotnet-plat-ext-5.0) respectively – Thom A Jan 26 '21 at 15:58
  • Also, you should be disposing connection, command and reader with `using`. See: [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Jan 26 '21 at 21:08
  • I used a task and then it's wait funtionality to throw a eception message. thank you all for your suggestions and help. I am very grateful. – Nirusma Jan 27 '21 at 03:37

0 Answers0