Sharing database connection with threads, instead of creating new ones

1.2k views Asked by At

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

There are 1 answers

0
Jerry Dodge On BEST ANSWER

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.