brk303 0 Posted September 2, 2023 I'm using a socket based async communication, but now also need ability to send blocking/synchronous request/reply. Basically, it needs to wait for result, and I'm wondering, what are ways to implement waiting. Communication is multithreaded and there might be various other messages going both ways while waiting for result. The only idea I have is to uniquely identify requests with say a random generated GUID, and pass the GUID back in response, so that client identifies the matching response. This must not be such a rare problem, and I wonder if there is some kind of standard solution for this? Or any other ideas how to go about? Share this post Link to post
aehimself 396 Posted September 3, 2023 If you are sure you can not put the component in sync mode somehow, what you can do is: - Create a thread, have a private boolean called "_requestcompleted" - Create the component in the thread's context - Set the event handlers, flip _requestcompleted to True in the handler when... well, the request is completed - in the thread's context, send the request and then have a loop like... Repeat // Message pump, if needed for the component Sleep(100); Until _requestcompleted Or Self.Terminated; This method is inefficient as the CPU is spinning in a loop but at least easy to understand. If your component needs no message pump, you can switch to events and use WaitForMultipleObjects for a more resource-friendly approach. Share this post Link to post
brk303 0 Posted September 3, 2023 Thanks for the response. Would it be a good idea to have one port/connection for async communication and another one for sync ? Share this post Link to post
Fr0sT.Brutal 900 Posted September 4, 2023 So you need to have sync method but made with async tools? Or need just one worker to do sync method while others continue executing? The exact task really influences the solution. If you have several async workers in a single thread and want one of them to execute a sync action while others still work, use additional worker state, bg thread and async notification: fState := clstRequesting thr := CreateAnonThread( ... do request ... PostThreadMessage(Self.OwnerThread, MSG_REQDONE, ...) // or any other async notification ) and in the worker's owner thread: MSG_REQDONE: worker.State := clstRequestDone worker.ContinueStuff And don't forget to: - Track timeout - Free the thread after finish - Ensure thread could be forcefully terminated if user closes the app Share this post Link to post