写一程序,监视一串口,分析获取的命令,然后将响应发回;
程序在执行过程中由于其他进程的运行或者操作而变得响应特别慢,甚至出现丢失字符和无法通讯的问题,请问,如果解决这一问题?

解决方案 »

  1.   

    用异步通讯。
    DWORD ComAccess::ReadData(LPVOID pdest, 
                              DWORD  len, 
                              DWORD  dwMaxWait)
    {
    BOOL  bSuccess;
    DWORD result = 0,
          read   = 0, // num read bytes
          mask   = 0; // a 32-bit variable that receives a mask 
                      // indicating the type of event that occurred if ( len < 1 ) return(0); // create event for overlapped I/O m_ov.hEvent = CreateEvent(NULL,   // pointer to security attributes 
                              FALSE,   // flag for manual-reset event 
                              FALSE,  // flag for initial state 
                              "");    // pointer to event-object name  if ( m_ov.hEvent == INVALID_HANDLE_VALUE )
    {
    // Handle the error.
    ComAccess::ErrorToString("ReadData(): CreateEvent() failed");
      
    return(-1);
    } // Specify here the event to be enabled bSuccess = SetCommMask(m_hCom, EV_RXCHAR); if ( ! bSuccess )
    {
    // Handle the error.
    CloseHandle(m_ov.hEvent);
    ComAccess::ErrorToString("ReadData(): SetCommMask() failed");
      
    return(-1);
    }
    // WaitForSingleObject bSuccess = WaitCommEvent(m_hCom, &mask, &m_ov); if ( ! bSuccess )
    {
    int err = GetLastError(); if ( err == ERROR_IO_PENDING)
    {
    result = WaitForSingleObject(m_ov.hEvent, dwMaxWait);  //wait dwMaxWait
                                            // milli seconds before returning
    if ( result == WAIT_FAILED )
    {
    // Handle the error.
    CloseHandle(m_ov.hEvent);
    ComAccess::ErrorToString("ReadData(): WaitForSingleObject() failed");
      
    return(-1);
    }
    }
    }

    // The specified event occured?

    if ( mask & EV_RXCHAR) 
    {
    bSuccess = ReadFile(m_hCom, // handle of file to read 
                    pdest,  // address of buffer that receives data 
                len,    // number of bytes to read 
            &read,  // address of number of bytes read 
        &m_ov); // address of structure for data  if ( ComAccess::IsNT() )
    {
    bSuccess = GetOverlappedResult(m_hCom, &m_ov, &read, TRUE); if ( ! bSuccess )
    {
    // Handle the error.
    CloseHandle(m_ov.hEvent);
    ComAccess::ErrorToString("WriteData(): GetOverlappedResult() failed"); return(-1);
    }
    }
    else
    if ( ! bSuccess )
    {
    // Handle the error.
    CloseHandle(m_ov.hEvent);
    ComAccess::ErrorToString("ReadData(): ReadFile() failed"); return(-1);
    }
    }
    else
    {
    // Handle the error.
    CloseHandle(m_ov.hEvent);
    wsprintf(m_lpszErrorMessage, "Error ReadData(): No EV_RXCHAR occured\n"); return(-1);
    }

    CloseHandle(m_ov.hEvent);

    return read;
    }