Search code examples
delphitcpdelphi-2009indy

Indy, Send Thread and Destroyed Contexts


I use Indy's TIdTCPServer (D2009, Indy 10) to communicate with client applications. In the OnExecute method I create a task and queue it. A worker thread executes the task and puts it in the send queue. The send queue then sends the response to the client.

In the send thread I loop through the server's context list and look for the context matching the IP and port information stored in the task. Then follow a number of send commands that sometimes throw access violations (I'm guessing that the context gets destroyed during sending).

Now to the question: how can I make sure that the context is not closed before I have sent the response? Is it possible with Indy to send from a separate thread or should everything be done in the Indy thread?


Solution

  • You can try keeping the TIdTCPServer.Contexts list locked while you are sending data, as The Context is not freed until after it is removed from the list. The downside is that no client connects/disconnects/sends will be processed while that one send is in progress.

    Alternatively, simply wrap your sending code in a try/except block and ignore any errors that may occur.

    Alternatively, if you can re-write your code to move the send queue into the Context itself, that would be best, yes. Then your OnExecute event handler could check the queue periodically and send data when available. That will also help with performance, as you are not serializing your sends anymore if you have outgoing data ready for multiple clients at the same time.