3

When asynchronous I/O (or "overlapped" I/O in Win32 jargon) is used, we need to deal with the OVERLAPPED structure and his hEvent member. If the I/O function will delay the read or write operation, we will get an ERROR_IO_PENDING error code, then we will wait the asynchronous operation to complete with a WaitForXxxEvent function, then we will call GetOverlappedResult.

However, if the I/O operation is immediately completed, we will not get ERROR_IO_PENDING, and in a read operation our read buffer will be filled immediately. But what about the OVERLAPPED::hEvent member? Will it be set to signaled state? I've not found a clear statement about that.

This question may seem pointless (why deal with the event if I know that the operation is already completed?), however I have a library that mimics the overlapped pattern and I need to have the same exact behavior.


As pointed by edgar.holleis in his comment, Raymond Chen explained this in his blog: Link

If an asynchronous I/O completes synchronously, is the hEvent in the OVERLAPPED structure signaled anyway?

Yes.

When an I/O completes (whether synchronously or asynchronously), the event is signaled and completion status notifications are queued. The Get­Overlapped­Result/Ex function can be used to wait on an I/O that has already completed; it will merely return immediately. If you ask Has­Overlapped­Io­Completed whether the I/O has completed, and the I/O completed synchronously, it will correctly report, "Yeah, of course it completed. Heck, it completed a long time ago!"

In other words, you can logically treat the case of an asynchronous I/O request completing synchronously as if it had completed asynchronously. It just completes asynchronously before you even blinked.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
lornova
  • 6,667
  • 9
  • 47
  • 74
  • 1
    The event will also be signaled if the operation completes immediately. It was tested with named pipes in Windows 7. – bkausbk Jun 06 '12 at 11:04

1 Answers1

2

No it won't. It took me ages to figure that one out the hard way ;)

Goz
  • 61,365
  • 24
  • 124
  • 204
  • That's counter-intuitive... the documentation says that I/O functions that accept an OVERLAPPED will always reset the event (so we don't have to manually reset it before the call), and that the event will be signaled when the I/O operation will be completed. Now, if the I/O operation completes immediately, the event should be signaled when the I/O function return TRUE... hmm... – lornova Mar 25 '10 at 11:05
  • I'm not going to say it confused the f**k out of me but I had MAJOR problems with the hEvent. In the end I just sacked it off and went with a "WaitForIOCompletion" function that would just sleep till it completed. – Goz Mar 29 '10 at 07:37
  • @edgar.holleis thanks, you should add this as a full answer – lornova Oct 15 '15 at 08:08