1
votes

I wanted to check into this before I attempt it. I am working on a couple threads which require fetching data from the database within the threads. Currently, based on all I've seen, I am creating a new database connection (TADOConnection) from within the threads. All works fine, except it would be great if I could obtain the connection object from somewhere outside the thread. Basically, I don't want to keep creating a new TADOConnection for each thread execution.

Is it possible to publish a TADOConnection property on the outside of the thread (thus assigning it when I create the thread) and then use that connection within the thread? All I would need to do then is create the TADODataSet inside the thread and assign its connection to this TADOConnection. I'm a little iffy about this, especially because I'm required to call CoInitialize and CoUninitialize when working with ADO in a thread.

1
possible duplicate of Is Delphi's TADOConnection thread-safe? Also, you always have to call CoInitialize/CoUnitialize in every individual thread that uses COM, as COM is thread context specific. - Ken White
Well, would it matter if the threads/s just created a TADOConnection and, well, just hung on to it for the duration of the app run? Do you need to continually create/destroy these threads? - Martin James
Already have my answer - the thing is I am creating these threads on an as-needed basis, which could mean 10 threads at once, or 1 thread every half hour. They do free themselves, they don't stay active, once it completes I have no use in it anymore. I just wanted to see if I could avoid creating it many times. - Jerry Dodge
Pool your threads and make them reentrant so you can reuse threads instead of freeing them after each task. - Remy Lebeau
I am actually doing 2-layer threading. I have one main thread, which yes, it's continuing in a loop. But the other ones are only created on demand, and are never specifically for one subject. Basically it's sending single requests to the server, waiting for a response, then triggering an event when the response is received. Once I get that response, I don't need it anymore. Each of these requests are sent to the server from its own thread. For example, if I need 3 numbers, each takes a long time to calculate, I send 3 requests at the same time, thus spawning 3 threads. - Jerry Dodge

1 Answers

1
votes

The answer looks like no. Because the TADOConnection (and other ADO components) are COM based, they cannot be passed across threads. So in this case, I have no choice but to create a new TADOConnection from within each thread. The threads which continue running make use of this connection each time it loops, but the single-run threads make use of it just once.