How to stop long running threads elegantly?

I have a problem with threads with Delphi. I think this is common in other languages. I have a long process that I am doing in a thread that populates the list in the main window. But if some parameters change in average time, then I have to stop the current executable thread and start from the very beginning. Delphi suggests terminating the stream by setting Terminated: = true and checking this variable value in the stream. However, my problem is that the long executable is buried in the library call, and in this call I cannot check the Terminated variable. Therefore, I had to wait for the completion of this library call, which would affect the entire program.

What is the preferred way to do in this case? Can I kill the stream immediately?

+5
source share
4 answers

The preferred way is to change the code so that it does not block without checking for cancellation.

Since you cannot change the code, you cannot do this; you either have to live with a background operation (but you can disconnect it from any user interface so that its completion is ignored); or, alternatively, you can try to terminate it (TerminateThread API will roughly terminate any thread, given its descriptor). Termination is not clean, although, as Rob says, any locks held by the thread will be left behind, and any state of the cross-thread protected by such locks may be in a damaged state.

? , RPC (, TCP, - ), , ? . , , , , , .

+9

, . , Delphi , .NET Java, , , .

, , (). , .

+3

, , .

+3

:

, Win32.

To complete the thread, I use QueueUserAPC to queue a call to a function that throws an exception. However, an exception that is not inferred from the "Exception" type, so only catch my thread wrapping procedure.

I have used this with C ++ Builder applications very successfully. I do not know all the intricacies of Delphi vs C ++ exception handling, but I would expect that it could be easily changed to work.

0
source

All Articles