title: Multithreaded (TThread) Delphi application will not terminate
body: <p>I have written an application (using Delphi 2009) that allows a user to select a series of queries which can be run across a number of different systems. In order to allow queries to be run concurrently, each query is run in its own thread, using a <code>TADOQuery</code> object. This all works fine.</p>
  
  <p>The problem that I have is when I try to close the application when a query is still running (and therefore a separate thread is active). When I create each thread, I record the thread's <code>THandle</code> in an array. When I try to close the application, if any threads are still running, I retrieve the thread's handle and pass it to <code>TerminateThread</code>, which should theoretically terminate the thread and allow the application to close. However, this doesn't happen. The main form's <code>onClose</code> event is triggered and it looks like the application is closing, but the process remains active and my Delphi interface appears as though the application is still running (i.e. "Run" button greyed out, debug view active etc.). I don't get control back to Delphi until I manually end the process (either Ctrl-F2 in Delphi or via Task Manager).</p>
  
  <p>I am using <code>TerminateThread</code> because the query can take a long time to run (a few minutes in cases where we're dealing with a million or so records, which in the end user environment is perfectly possible) and while it is running, unless I'm mistaken, the thread won't be able to check the <code>Terminated</code> property and therefore won't be able to end itself if this were set to True until the query had returned, so I can't terminate the thread in the usual way (i.e. by checking the Terminated property). It may be the case that the user wants to exit the application while a large query is running, and in that case, I need the application to immediately end (i.e. all running threads immediately terminate) rather than forcing them to wait until all queries have finished running, so <code>TerminateThread</code> would be ideal but it isn't actually terminating the thread!</p>
  
  <p>Can anyone help out here? Does anyone know why <code>TerminateThread</code> doesn't work properly? Can anyone suggest anything to get the threads running large ADO queries to immediately terminate?</p>