Indy 10 IdTCPClient Reading Data using a separate thread?

后端 未结 2 1857
心在旅途
心在旅途 2020-12-29 15:57

Question: What I\'m looking for is the most typical or best practice way to use a separate thread to receive data using an IdTCPClient in Indy 10.

2条回答
  •  鱼传尺愫
    2020-12-29 16:49

    You're on the right track. Indy is intended to be used like that. It uses blocking sockets, so the ReadBytes call doesn't return until it's read what you've asked for. Contrast that with non-blocking sockets, where a call may return early, so you either poll or get notified asynchronously to determine when a request has been filled.

    Indy is designed with the expectation that the socket objects have their own threads (or fibers). Indy comes with TIdAntifreeze for the folks who want to drag and drop socket components onto their forms and data modules and use the Indy components from the main GUI thread, but that's not generally a good idea if you can avoid it.

    Since your thread cannot work without FSocket being assigned, I advise you to simply receive that value in the class's constructor. Assert in the constructor if it's not assigned. Furthermore, it is an error to create your thread non-suspended, so why even give the option? (If the thread is not created suspended, then it will start running, check whether FSocket is assigned, and fail because the creating thread hasn't gotten to assign that field yet.)

提交回复
热议问题