简体   繁体   中英

Halt Linq query if it will take 'too' long

Currently I have the need to create a reporting program that runs reports on many different tables within a SQL database. Multiple different clients require this functionality but some clients have larger databases than others. What I would like to know is whether it is possible to halt a query after a period of time if it has been taking 'too' long.

To give some context, some clients have tables with in excess of 2 million rows, although a different client may have only 50k rows in the same table. I want to be able to run the query for say 20 seconds and if it has not finished by then return a message to the user to say that the result set will be too large and the report needs to be generated outside of hours as we do not want to run resource intensive operations during the day.

Set the connection timeout on either your connection string or on the DataContext via the CommandTimeout property . When the timeout expires, you will get a TimeoutException , and your query will be cancelled.

You cannot be sure that the query is cancelled on the server the very instant the timeout occurs, but in most cases it will cancel rather quickly. For details read the excellent article "There's no such thing as a query timeout..." . The important part from there is:

A client signals a query timeout to the server using an attention event. An attention event is simply a distinct type of TDS packet a SQL Server client can send to it. In addition to connect/disconnect, T-SQL batch, and RPC events, a client can signal an attention to the server. An attention tells the server to cancel the connection's currently executing query (if there is one) as soon as possible. An attention doesn't rollback open transactions, and it doesn't stop the currently executing query on a dime -- the server aborts whatever it was doing for the connection at the next available opportunity. Usually, this happens pretty quickly, but not always.

But remember, it will differ from provider to provider and it might even be subject to change between server versions.

You can do that easily if you run the quer on a background thread. Make the main thread start a timer and spawn a background thread that runs the query. If when 20 seconds are over the background thread hasn't returned a result, the main thread can cancel it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM