kd.
kd.

Reputation: 292

threading in asp.net

i am trying to implement a timeout on my database querys...so if an operation runs for too long i need to cancel the query and return a timeout message to an asp.net page....

heres the code i was using for the timeout portion....problem is i am sometimes getting partial result sets from the query...

RunSearch search = new RunSearch(GetSearchResults);
Thread searchThread = new Thread(delegate() {
dsRes =   search.Invoke(ProcessingID, 
objSqlConnection,SearchStartTime); });

searchThread.Start();
// searchThread.Join(ResultPollingPeriod * 1000);

if (!searchThread.Join(ResultPollingPeriod * 1000))
{
    searchThread.Abort();
    dsRes = null;
    return ReturnTimeoutMessage();
}
else
{
    return dsRes;
}

any help is much appreciated...

Upvotes: 1

Views: 270

Answers (1)

Ryan Elkins
Ryan Elkins

Reputation: 5797

There are a couple of ways to handle this depending on your goals but you shouldn't have to write your own implementation of this. You could set the timeout on the database itself so you don't have to deal with this in code. If you want it to be client side defined though here are two types of timeouts to consider: Connection timeouts and command timeouts.

A connection timeout is when it can't connect to the server. This is set in the connection string settings by adding a Connect Timeout=30. If it doesn't establish a connection within 30 seconds it will timeout.

If it does establish a connection, then you need a command timeout on the SqlCommand object:

using (SqlCommand myCommand = new SqlCommand())
{
    myCommand.CommandTimeout = 30;
    //the rest of your command setup here
}

It's my understanding that the CommandTimeout runs concurrently with the connection timeout - so if it takes 29 seconds to connect the command has to execute and return within 1 second.

These timeouts will throw exceptions which you can then catch and do as you'd like (return a timeout message to an ASP.NET page or somesuch).

Upvotes: 1

Related Questions