Reputation: 1870
I start a long operation (usually long query (SELECT) to database). It might take long time, and I want to add capability to stop this action. Code looks like:
ThreadPool.QueueUserWorkItem(a => action.DoLongAction());
public void DoLongAction()
{
var sql = Tables.Where(el => el.Some == "XXX"); // dynamically constructed LINQ query to database
var result = db.Query(sql);
}
I can't use signals of flags, to stop this thread. Because, long operation isn't in my code, but in database process (sql query about 5 mins).
How can I stop this thread correctly?
UPD1. Not plain SQL, but LINQ (EF4, BLToolkit)
Upvotes: 2
Views: 7694
Reputation: 1035
You can also add a timeout value for the SQLCommand. aka, cancel after x seconds if not finished.
Upvotes: 0
Reputation: 2673
If you really need to abort this Thread manually, then you can use the Thread class. For details about how to use it, you can look at this online resource.
Please note that usually, using Thread.Abort();
is not a best practice, except when you are ending your program and wants to terminate all the running threads.
In your case, as you are trying to end a SQL query, you should look at other ways to stop it (SqlCommand.Cancel(), ISession.CancelQuery(), ...)
Upvotes: 1
Reputation: 174289
Consider using the BackgroundWorker class. It supports canceling. But you can only cancel the query in a safe manner, if the database provider supports canceling it. Your code doesn't look like it supports canceling.
Update: After some discussion, the following info also is worth to be put into the answer:
SqlCommand supports cancellation as Guillaume points out, but the database driver used needs to also support it. So best way to do it:
Use SqlCommand or the class derived from it for your DBMS, execute the query and try to cancel it and see whether it is supported. If it is not supported, you will get an exception.
If it is supported, the example for SqlCommand.Cancel will help you to implement the behavior you want.
Upvotes: 3
Reputation: 13128
If you want to Cancel a SQL command, have a look at SqlCommand.Cancel documentation.
Upvotes: 2