Waiting until a file is available for reading with Win32

后端 未结 4 612
情话喂你
情话喂你 2020-12-07 01:22

I\'m watching a directory by calling ReadDirectoryChangesW synchronously. When a new file is available, I try to access it immediately with CreateFile

4条回答
  •  佛祖请我去吃肉
    2020-12-07 02:07

    I don't think there is a notification for the kind of event you're looking for, but as an improvement, I'd suggest progressive delays. This way you will get fast response times for stuff like a drag/drop and won't hog the CPU with a tight loop if the user keeps the file open for an hour in Excel.

    int delay= 10;
    while ((hFile = CreateFile (path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() == ERROR_SHARING_VIOLATION) {
            Sleep (delay);
            if (delay<5120) // max delay approx 5.Sec
                delay*= 2;
        }
        else
            break; // some other error occurred
    }
    

提交回复
热议问题