Jump to content
brk303

Implementing sync requests in async communication

Recommended Posts

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

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

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×