Recent

Author Topic: Calling TIdTCPClient.IOHandler.Write from main thread  (Read 757 times)

PawelO

  • New Member
  • *
  • Posts: 31
    • Polish railway traffic and interlocking simulator developed with Lazarus
Calling TIdTCPClient.IOHandler.Write from main thread
« on: July 30, 2025, 05:17:49 pm »
Hello,

Recently, I found in this thread: https://en.delphipraxis.net/topic/1010-using-indy-for-cross-platform-tcpip/ that calling TIdTCPClient.IOHandler.Write... (which is something that I've been doing since forever - thanks to almost every tutorial - and that seems to work fine) from main thread can be "unsafe" and it's not recommended.

However, I cannot call it from the thread I have already created and used for listening (TIdTCPClient.IOHandler.Read...), since this thread is usually blocked waiting for incoming messages. Do I need a third thread then? Or can I use same thread, sequentially reading with some small timeout (but how small can it be), and writing from queue?

I basically want to create a TCPClient wrapper that has Connect, Disconnect, WriteLn methods, some OnReadLn event and Connected property all working with main (UI) thread, in an asynchronous, non-blocking way. Are somewhere examples how to do it in the most simple and "right" way?

Best regards

Remy Lebeau

  • Hero Member
  • *****
  • Posts: 1595
    • Lebeau Software
Re: Calling TIdTCPClient.IOHandler.Write from main thread
« Reply #1 on: July 30, 2025, 07:13:15 pm »
Do I need a third thread then? Or can I use same thread, sequentially reading with some small timeout (but how small can it be), and writing from queue?

Basically, yes.  Either approach will work. Use whichever one makes more sense for your app's design.

I basically want to create a TCPClient wrapper that has Connect, Disconnect, WriteLn methods, some OnReadLn event and Connected property all working with main (UI) thread, in an asynchronous, non-blocking way.

Then perhaps Indy is not the best choice for your app. Since Indy is primarily a synchronous library, threads and timeouts are basically your only options for asynchronous behaviors. Otherwise, look into other options if you need truly asynchronous sockets.

Are somewhere examples how to do it in the most simple and "right" way?

Nothing official, no.  Just posts floating around the various forum sites over the years.
Remy Lebeau
Lebeau Software - Owner, Developer
Internet Direct (Indy) - Admin, Developer (Support forum)

 

TinyPortal © 2005-2018