We retrieve the TFDConnection from the TXDataOperaionContext.Current. This works fine and is thread safe:
(TXDataOperationContext.Current.Connection as IDBConnectionAdapter).AdaptedConnection as TFDConnection;
However, I would like to get a TFDConnection within a thread as well for longer running processes. In this case sending e-mails. The thread (ITask) is created within the endpoint. The backend call does not wait for the thread to finish.
I would like to get a connection from withitn the thread on a thread-safe manner. I tried the following:
The thread pool is a set to be a global variable and is accessed within a thread:
result := (Global_Pool.GetConnection as IDBConnectionAdapter).AdaptedConnection as TFDConnection;
Questions:
Does the GetConnection reserve the retrieved connection until it is returned to the pool?
If yes, how is the connection returned to the pool after the thread finishes?
The connection is returned when the IDBConnection interface retrieved from the pool gets its reference count set to zero. Thus, you have to keep a reference to the interface during the time you use the adapted connection, for instance:
var
Conn: IDBConnection;
FDConn: TFDConnection;
begin
Conn := Global_Pool.GetConnection; // "save" the reference
FDConn := (Conn as IDBConnectionAdapter).AdaptedConnection as TFDConnection;
// use FDConn
// When the method finishes (or when Conn is set to nil), then the interface is released
// and the underlying TFDConnection component is destroyed.
end;
(*) Well, yes and no. It will reserve the retrieved connection, but it will be immediately returned to the pool when the interface is out of scope. In this specific case probably Delphi compiler will keep the interface reference until the method is finished. But it's safer if you keep an explicit reference to the interface so you know more clearly when it's released.