How to mix Sockets, Messages and Events

638 views Asked by At

There is a thread that uses ADO Connection object, operates with a socket(s) and reacts on outer events using WaitForSigleObject or WaitforMultipleObjects. The thread has an endles loop with 3 actions:

While PeekMessage(MSG, 0, 0, PM_REMOVE) do ProcessMessages(MSG); //for processing messages of COM system

if Socket.CanRead then ... //CanRead is true when there is data in socket to read

if WaitForSingleObject(fHandle, 0) = WAIT_OBJECT_0 then ... //fHandle is handle of outer event

Almost all time the thread wastes CPU asking about all three types of events. Is there way to make thread to sleep until one of three types of events happend, like WaitForMultiplyObjects or GetMessage?

2

There are 2 answers

0
account deleted On

For the record, ProcessMessages is the single most evil bit of code ever devised. It will create problems the like of which you simply can not imagine.

There are a number of non blocking socket components out there, so you do not have to poll for data FP's ICS comes to mind), perhaps you might want to try that to help with your socket problems.

1
Andrei Galatyn On

It is not clear what kind of library you use for network operations with socket. In general there are two possible ways to work with sockets, blocking or non-blocking sockets. If you use blocking sockets (Indy for example), then probably it is good idea to use separate thread for socket operations. If you use non-blocking sockets (like ICS library), then you can use MsgWaitForMultipleObjectsEx function for synchronization with flags QS_ALLINPUT for all your input events. You can find more information on this function here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684245%28v=vs.85%29.aspx Main difference of MsgWaitForMultipleObjectsEx from WaitforMultipleObjects is that first one can wake up not only when some object is signalated, but also when some specific or any message was posted in the queue. Seems it is what you asked.