关于异步I/O请求被同步处理的问题。。

时间:2023-02-11 13:45:40

    有些异步I/O请求会被同步处理。。比方说,你要读的内容正好在系统缓存中,那么就可以直接copy到你的缓存中,异步I/O请求就可以同步的处理。。于是,在我们coding的时候,就要把情况考虑周全。。

if (!ReadFile(hFile,
                 pDataBuf,
                 dwSizeOfBuffer,
                 &NumberOfBytesRead,
                 &osReadOperation )
   {
      if (GetLastError() != ERROR_IO_PENDING)
      {
         // Some other error occurred while reading the file.
         ErrorReadingFile();
         ExitProcess(0);
      }
      else
         // Operation has been queued and
         // will complete in the future.
         fOverlapped = TRUE;
   }
   else
      // Operation has completed immediately.
      fOverlapped = FALSE;

   if (fOverlapped)
   {
      // Wait for the operation to complete before continuing.
      // You could do some background work if you wanted to.
      if (GetOverlappedResult( hFile,
                               &osReadOperation,
                               &NumberOfBytesTransferred,
                               TRUE))
         ReadHasCompleted(NumberOfBytesTransferred);
      else
         // Operation has completed, but it failed.
         ErrorReadingFile();
   }
   else
      ReadHasCompleted(NumberOfBytesRead);
 

   以上函数,当ReadFile 和 WriteFile返回非零值表示这个异步I/O请求被同步的处理了。。

    如果被异步处理了,或者出现error.返回false。。此时,我们必须调用GetLastError来确定是那种情况。若GetLastError返回ERROR_IO_PENDING,说明I/O请求被排入等待队列,将会被处理。。其他的返回值,说明出现了error..