Page 1 of 1

is it not possible at all to use an existing MSConnection in

Posted: Wed 10 Nov 2010 08:52
by brace
I am succesfully implementing background threads that use a dedicated connection.

I have only one problem, since I am connecting to the DB inside the thread, I lose a lot of time in estabilishing the connection and a very little time to execute the thread:

Code: Select all

procedure TSDACBackgroundThread.Execute;
begin
// coinitialize part
  FData.MSConnection.Connect; // takes "2 seconds"
  FData.MSQuery.Execute; // takes "5 milliseconds"
  FData.MSConnection.Disconnect;
end;
Ok, it is a background thread, but I lose 2 extra seconds, since in some cases I need to run many background threads and wait for all of them to be completed bfore continuing anyway those "2 seconds" can make a difference in speed.

Is it a way I can pass an already existing connection or am I forced to call TMSConnection.Connect INSIDE the thread?

Posted: Wed 10 Nov 2010 13:59
by AndreyZ
Hello,

You can use one connection for several threads only if you provide thread-safety by yourself. In this case you can call TMSConnection.Connect once in the main thread and then use this connection in other threads avoiding spending time on connection establishment.

Posted: Wed 10 Nov 2010 16:18
by brace
But are there any problems if I simply call

Code: Select all

MSQuery1.Open;
in thread?

I mean which thread-safe realted problems may I face if I simply open queries in threads?

Posted: Thu 11 Nov 2010 09:19
by AndreyZ
The best way to work in a multithreaded application is to you have a connection in each thread. In this case one connection executes one query at a time. One connection can't execute several queries simultaneously. Therefore, when you are trying to use one global connection to run several queries you have to provide their execution safety. Otherwise, when two threads are trying to access data through one connection an error will arise.

Posted: Thu 11 Nov 2010 12:08
by brace
ok, clear, so an alternative approach is to create some connections and be sure to use only one per thread. So since they are already created I don't have to wait for connection.

This particular case is possible since I have 3 background tasks (so a fixed number of background tasks = 3 connections), of course for all other types of theading it makes no sense since i cannot predict how many connectinos I will need.

Posted: Thu 11 Nov 2010 12:57
by AndreyZ
ok, clear, so an alternative approach is to create some connections and be sure to use only one per thread. So since they are already created I don't have to wait for connection.
Yes, you can use this solution.

Posted: Thu 11 Nov 2010 13:28
by brace
Thanks a lot.