2010-08-09 40 views
0

程序运行良好几分钟,然后ReadFile开始失败,错误代码为ERROR_WORKING_SET_QUOTA。调用ReadFile返回ERROR_WORKING_SET_QUOTA

我使用的ReadFile重叠的I/O,像这样:

while (continueReading) 
{ 
    BOOL bSuccess = ReadFile(deviceHandle, pReadBuf, length, 
          &bytesRead, readOverlappedPtr); 
    waitVal = WaitForMultipleObjects(
       (sizeof(eventsToWaitFor)/sizeof(eventsToWaitFor[0])), 
       eventsToWaitFor, FALSE, INFINITE); 
    if (waitVal == WAIT_OBJECT_0) { 
     // do stuff 
    } else if (waitVal == WAIT_OBJECT_0 + 1) { 
     // do stuff 
    } else if (waitVal == WAIT_OBJECT_0 + 2) { 
     // complete the read 
     bSuccess = GetOverlappedResult(deviceHandle, &readOverlapped, 
             &bytesRead, FALSE); 
     if (!bSuccess) { 
      errorCode = GetLastError(); 
      printf("ReadFile error=%d\n", errorCode); 
     } 
    } 
} 

为什么会出现这个错误?

回答

0

问题是ReadFile被调用的次数多于GetOverlappedResult。导致进程耗尽资源来处理所有未完成的读取。

此外,我们应该检查ReadFile的结果并确保结果是ERROR_IO_PENDING,如果不是,并且ReadFile返回FALSE,那么还有另一个问题。

确保每次调用ReadFile时都调用一次GetOverlappedResult。像这样:

BOOL bPerformRead = TRUE; 
while (continueReading) 
{ 
    BOOL bSuccess = TRUE; 
    // only perform the read if the last one has finished 
    if (bPerformRead) { 
     bSuccess = ReadFile(deviceHandle, pReadBuf, length, 
          &bytesRead, readOverlappedPtr); 
     if (!bSuccess) { 
      errorCode = GetLastError(); 
      if (errorCode != ERROR_IO_PENDING) { 
      printf("ReadFile error=%d\n", errorCode); 
      return; 
      } 
     } else { 
      // read completed right away 
      continue; 
     } 
     // we can't perform another read until this one finishes 
     bPerformRead = FALSE; 
    } 
    waitVal = WaitForMultipleObjects( 
       (sizeof(eventsToWaitFor)/sizeof(eventsToWaitFor[0])), 
       eventsToWaitFor, FALSE, INFINITE); 
    if (waitVal == WAIT_OBJECT_0) { 
     // do stuff 
    } else if (waitVal == WAIT_OBJECT_0 + 1) { 
     // do stuff 
    } else if (waitVal == WAIT_OBJECT_0 + 2) { 
     // complete the read 
     bSuccess = GetOverlappedResult(deviceHandle, &readOverlapped, 
             &bytesRead, FALSE); 
     // the read is finished, we can read again 
     bPerformRead = TRUE; 
     if (!bSuccess) { 
      errorCode = GetLastError(); 
      printf("GetOverlappedResult from ReadFile error=%d\n", errorCode); 
     } 
    } 
} 
+1

更接近。但实际上验证ReadFile返回FALSE并且GetLastError()返回ERROR_IO_PENDING *非常重要。当数据从文件系统缓存中传出时,读取文件通常会立即完成。 – 2010-08-09 18:20:02

+0

谢谢,更新以纳入您的建议。 – 2010-08-10 13:01:08