1
2
Code:
BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite)
{
OVERLAPPED osWrite = {0};
DWORD dwWritten;
DWORD dwRes;
BOOL fRes;
// Create this <strong class="highlight">write</strong> operation's OVERLAPPED structure's hEvent.
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL)
// error creating overlapped event handle
return FALSE;
// Issue <strong class="highlight">write</strong>.
if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite)) {
if (GetLastError() != ERROR_IO_PENDING) {
// WriteFile failed, but isn't delayed. Report error and abort.
fRes = FALSE;
}
else
// <strong class="highlight">Write</strong> is pending.
dwRes = WaitForSingleObject(osWrite.hEvent, INFINITE);
switch(dwRes)
{
// OVERLAPPED structure's event has been signaled.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, FALSE))
fRes = FALSE;
else
// <strong class="highlight">Write</strong> operation completed successfully.
fRes = TRUE;
break;
default:
// An error has occurred <strong class="highlight"><vb_highlight>in</strong></vb_highlight> WaitForSingleObject.
// This usually indicates a problem with the
// OVERLAPPED structure's event handle.
fRes = FALSE;
break;
}
}
}
else
// WriteFile completed immediately.
fRes = TRUE;
CloseHandle(osWrite.hEvent);
return fRes;
}
The code above uses the WaitForSingleObject function with a time-out value of INFINITE, this causes the WaitForSingleObject function to wait for long until the operation is completed and this can make the thread appear to be "hung" when the write operation is simply taking a long time to complete or flow control has blocked the transmission.
Read the given links (1,2)