An application must always set communication time-outs using the COMMTIMEOUTS structure each time it opens a communication port. If this structure is not configured, the port uses default time-outs supplied by the driver, or time-outs from a previous communication application. By assuming specific time-out settings when the settings are actually different, an application can have read/write operations that never complete or complete too often.
When read/write operations time out, the operations complete with no error values returned to the ReadFile and WriteFile functions. To determine if an operation has timed out, verify that the number of bytes actually transferred is fewer than the number of bytes requested. For example, if the ReadFile function returns TRUE, but fewer bytes were read than requested, the operation has timed out.
To assist with multitasking, it is common to configure COMMTIMEOUT so that ReadFile immediately returns with the characters to be read. To do this, set ReadIntervalTimeout to MAXWORD and set both ReadTotalTimeoutMultiplier and ReadTotalTimeoutMultiplier to zero.
The following code example shows how to configure time-outs for a serial port.
// Retrieve the time-out parameters for all read and write operations
// on the port.
COMMTIMEOUTS CommTimeouts;
GetCommTimeouts (hPort, &CommTimeouts);
// Change the COMMTIMEOUTS structure settings.
CommTimeouts.ReadIntervalTimeout = MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier = 0;
CommTimeouts.ReadTotalTimeoutConstant = 0;
CommTimeouts.WriteTotalTimeoutMultiplier = 10;
CommTimeouts.WriteTotalTimeoutConstant = 1000;
// Set the time-out parameters for all read and write operations
// on the port.
if (!SetCommTimeouts (hPort, &CommTimeouts))
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to set the time-out parameters"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}