Search code examples
multithreadingdelphiindy

Delphi/Indy multithreading Server


I am trying to turn my app multithreading. What I want to achieve is: - Receive command via TidHTTPServer - Execute local action (might involve using tidHTTP to send/receive data to other services) - return execution result to the original caller

since I am pretty new to multi-threading I would like to know if my design-idea is correct

  1. TMsgHandler=Class(TThread)
  2. in TidHTTPServer.OnCommandGet I create a new instance of TMsgHandler and pass ARequestInfo and AResponseInfo
  3. TMsgHandler.Excecute interprest the data
  4. Can TMsgHandler.Execeute use Objects (descendants of TidHTTP) in my Main to communicate with other services?
  5. TMsgHandler sends answer through AResponseInfo and terminates.

will this work?


Solution

  • This is not the correct design.

    THTTPServer is a multi-threaded component. Its OnCommand... events are fired in the context of worker threads that Indy creates for you.

    As such, you do not need to derive your TMsgHandler from TThread. Do your TIdHTTP directly in the context of the OnCommand... thread instead. A response will not be sent back to the client until your event handler exits (unless you send one manually). However, you should not share a single TIdHTTP from the main thread (unless you absolute need to, in which case you would need to synchronize access to it). You should create a new TIdHTTP dynamically directly in your OnCommand.../TMsgHandler code as needed.