异步机制 - ReadFileEx(WriteFileEx)
1 ReadFileEx定义
BOOL WINAPI ReadFileEx(
__in HANDLE hFile,
__out LPVOID lpBuffer,
__in DWORD nNumberOfBytesToRead,
__in LPOVERLAPPED lpOverlapped,
__in LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
文件的偏移在lpOverlapped里面指定,这个结构体定义如下
typedef struct _OVERLAPPED
{
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
};
PVOID Pointer;
}; HANDLE hEvent; //在ReadFileEx这里,这个成员没用到
} OVERLAPPED, *LPOVERLAPPED;
Internal和InternalHigh其实就是IO_STATUS_BLOCK里面的成员,也就是说Internal表示本次IO的结果,InternalHigh表示本次IO的实际大小
typedef struct _IO_STATUS_BLOCK {
union {
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
可以调用GetOverlappedResult来判断IO的情况
BOOL WINAPI GetOverlappedResult(
__in HANDLE hFile,
__in LPOVERLAPPED lpOverlapped,
__out LPDWORD lpNumberOfBytesTransferred,
__in BOOL bWait //表示是否需要等待,如果IO还处于PENDING状态,其实内部就是调用WaitForSingleObject进行等待
);
2 GetOverlappedResult的bWait含义
GetOverlappedResult的bWait含义表示是否需要等待,如果IO还处于PENDING状态,内部大概实现是这样
hObject = lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile;
WaitStatus = WaitForSingleObject(hObject, INFINITE);