本文介绍了ReadFile始终会阻塞直到读取完成,即使对于异步操作也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Windows 7,但出现ReadFile怪异的行为.

通过指定了FILE_FLAG_OVERLAPPED的CreateFile打开文件并读取*大*的数据块时磁盘(假设500Mb以使效果更明显),ReadFile最多阻塞10秒钟,然后返回FALSE(GetLastError()报告ERROR_IO_PENDING),并且我正在*立即*回调异步I/O已完成( BindIoCompletionCallback).这是要复制的代码:

(我剥离了IOCP绑定以削减代码,这两种方式都可以复制)

//打开文件
HANDLE hFile = CreateFileW(L"c:\\ path \ to \ large \ file",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);

I'm running Windows 7 and I'm getting weird behavior of ReadFile.

When opening a file via CreateFile with FILE_FLAG_OVERLAPPED specified, and reading a *large* chunk of data off the disk (let's say 500Mb to make the effect more noticeable), ReadFile blocks for up to 10 seconds, then returns FALSE (GetLastError() reports ERROR_IO_PENDING) and I'm getting *immediate* callback that async I/O is complete (BindIoCompletionCallback). Here is a code to reproduce:

(I stripped IOCP binding to cut down the code, it is reproducible both ways)

// open file
HANDLE hFile = CreateFileW(L"c:\\path\to\large\file", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

int dataSize = 500 * 1024 * 1024;
char * data =(char *)malloc(dataSize);
memset(data,0xFF,dataSize); //预热,以便请求整个内存

重叠;
内存集(& lapd,0,sizeof(overlapped));

printf ("reading ... \ n");  fflush(stdout);
BOOL结果= ReadFile(hFile,data,dataSize,NULL和重叠); //这里最多延迟10秒
printf("done!\ n"); fflush(stdout);

printf(结果:%d GetLastError():%d \ n",结果是GetLastError()); fflush(stdout);

DWORD bytesRead;
结果= GetOverlappedResult(hFile,&重叠,& bytesRead,TRUE); //等待完成-立即返回

printf(读取的字节:%d \ n",bytesRead);&ffbff(stdout);

CloseHandle(hFile );

我是不是在做一些愚蠢的错误,这是故意的(高度怀疑),还是它的错误?

我不打算在XP上对此进行测试.

int dataSize = 500 * 1024 * 1024;
char* data = (char*)malloc(dataSize);
memset(data, 0xFF, dataSize); // warm-up so that the whole memory is requested

OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));

printf("reading...\n"); fflush(stdout);
BOOL result = ReadFile(hFile, data, dataSize, NULL, &overlapped); // up to 10 seconds delay here
printf("done!\n"); fflush(stdout);

printf("Result: %d GetLastError(): %d\n", result, GetLastError()); fflush(stdout);

DWORD bytesRead;
result = GetOverlappedResult(hFile, &overlapped, &bytesRead, TRUE); // wait until completion - returns immediately

printf("Bytes read: %d\n", bytesRead); fflush(stdout);

CloseHandle(hFile);

Am I doing something stupid wrong, is this intended (highly doubt that), or is it a bug?

I'm off testing this on XP. BRB!

推荐答案


这篇关于ReadFile始终会阻塞直到读取完成,即使对于异步操作也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 01:49