简体   繁体   中英

How to stop thread in ThreadPool?

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)

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.

如果要取消SQL命令,请查看SqlCommand.Cancel文档。

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() , ...)

You can also add a timeout value for the SQLCommand. aka, cancel after x seconds if not finished.

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