XData Service Operation and Threads

Hi, it is safe to create threads on a service operation

I have a service that saves data to the database on the Service operation and need to call a Webservice from a external server to retrieve aditional data, and save it to the database, for this I use a thread on the service method(Client doesnt need to wait for aditional data to be retrieve from external server for the call to the service operation to be ok).

Some thing like this:

function SaveServerData(...)
aThread : TThread;
IDConnection : IDBConnection;
/// Get connection from connection pool.
/// save sent data on DB

IDConnection := TXDataOperationContext.Current.GetConnectionPool.GetConnection;
aThread := TThread.CreateAnonymousThread(procedure ()
Manager : TObjectManager;
Manager := TObjectManager.Create(IDConnection);
/// call remote webservices and save responses to database
/// may take from seconds to a few minutes to complete, depends on the remote server load.
IDConnection := nil;

Is the above code ok? will the call to the ServerData return the connection to the connection pool and also the thread code will return the
connection to the connection pool when finished?

Thanks in advance,

Omar Zelaya

Yes, that construction should work. What you can't do is to use things from the context, like the manager, or request/response, because those will not be accessible from the thread, and might even be destroyed. Also, of course, you shouldn't use threads if the service operation should return something to the client that needs to be processed in the thread.

In this case, using the connection is ok because the connection is an interface and is referenced counted. So all is fine, when the connection is not used anymore, it will be returned to the pool, and the pool is global, is not part of the context.

That's useful information. I was thinking of adding a Omni Thread (OTL) BackgroundWorker and scheduling jobs to it when certain service calls are made. I was thinking to perhaps put this in another app, but it looks like it could live in the XData server so that all code was in one place.

1 Like