关于如何处理关闭的异步文件的关联事件(OVERLAPPED.hEvent)尚不清楚:是否会关闭它还是被视为句柄泄漏?
void Close()
{
if (INVALID_HANDLE_VALUE != file)
{
// TOCHECK: should the associated events be closed explicitly?
for (long i = 0; i < overlapped_max; ++i)
{
DWORD dummy;
auto & overlapped = overlapped_array[i];
// wait for asynchronous I/O completion if any
::GetOverlappedResult(file, &overlapped, &dummy, TRUE);
HANDLE hEvent = _InterlockedExchange(&overlapped_array[i].hEvent, 0);
if (hEvent) ::CloseHandle(hEvent);
}
// it is safe to close the file here because the file will be closed internally by the kernel
// only after all I/O asynchronous operations on this file complete
::CloseHandle(file);
file = INVALID_HANDLE_VALUE;
}
delete[] filename;
filename = nullptr;
}
编辑:事件需要明确关闭,但正如Hans所建议的那样,最好在关闭文件后关闭它们。
void Close()
{
HANDLE hFile = _InterlockedExchange(&file, INVALID_HANDLE_VALUE);
if (INVALID_HANDLE_VALUE != hFile)
{
// it is safe to close the file here because the file will be closed internally by the kernel
// only after all I/O asynchronous operations on this file complete
::CloseHandle(hFile);
for (long i = 0; i < overlapped_max; ++i)
{
::CloseHandle(overlapped_array[i].hEvent);
}
}
delete[] filename;
filename = nullptr;
}
现在,我仍然有一个关于&#34的问题;这里关闭文件是安全的,因为只有在此文件上的所有I / O异步操作完成后,内核才会在内部关闭文件&#34;。我不记得我是写这篇文章还是引用了微软的声明。据说该文件被打开两次,这将调用具有特定文件句柄的CloseHandle等待通过此特定句柄完成的所有I / O完成吗?如果没有,关闭文件句柄后关闭事件句柄根本不安全。