Search code examples
windows-cemessage-queue

How to empty a Windows CE point-to-point message queue


Note: This question is about Windows CE point-to-point message queues, not GDI message queues and not MSMQ.

When using a Windows CE point-to-point message queue to communicate between two threads, I sometimes need to discard all messages currently in the queue. There doesn't seem to be a function to do this. Options I am considering:

  • Close one end of the queue, and reopen it. Will this work?
  • Repeatedly read messages from the queue until it is empty. If I read into a tiny buffer (I presume that's more efficient than reading into a full size buffer) I understand that will cause the entire message to be discarded.

Solution

  • If the queue is configured with the MSGQUEUE_ALLOW_BROKEN flag closing the handle will not remove messages already in the queue and will not prevent the other side from appending new ones when your own application is not receiving. Closing a queue that doesn't have the flag set will generate an error as soon as the other party will try to write and this may lead to unexpected behaviours or not being able to communicate again. Reading all the message should work on both kinds of queues and will not be noticed in any way by the other application. The idea of using a small buffer is smart, you may save some time and, even if you get ERROR_INSUFFICIENT_BUFFER the message should be removed from the queue (at least this is what the documentation states).