c++socketswinapiasynchronousoverlapped-io

Why is asynchronous IO preferred


So I've been doing some WIN32 socket programming and I'm trying to understand why Overlapped IO is preferred. In particular, I'm wondering why something like this

if (WSARecv(
            socket,
            dataBuf,
            1,
            NULL,
            &flags,
            &ov,
            NULL)
            == SOCKET_ERROR) {
    if (WSAGetLastError() == WSA_IO_PENDING)
    {
        if (WSAWaitForMultipleEvents(1, &ov.hEvent, FALSE, INFINITE, FALSE) == WAIT_TIMEOUT)
        {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
// ... more code here
return TRUE;

Is preferred over a normal IO call like this

 recv(socket, dataBuf, bufLen), 0);

From my understanding, the first call will block if the IO event didn't complete at the WSAWaitForMultipleEvents, whereas the second call blocks directly on recv until data has arrived. So what is the actual benefit of having the IO call block slightly later? Is it that IF you had something you could do before waiting you'd do that?

If that is the case is Overlapped IO worth it/needed in applications in which you have can't do anything until data has arrived?


Solution

  • The case you show is not the typical reason to use any kind of asynchronous I/O, quite the opposite I would say (since it is, as you noted, not really asynchronous anyway).

    The typical reason to use asynchronous I/O is just because it is asynchronous, your program can continue with doing something else instead of waiting for the I/O operation to finish.