Mircea Ispas
Mircea Ispas

Reputation: 20780

How to stop ReadDirectoryChangesW from other thread

I use next code to know when a files is changed in a certain folder:

HANDLE hDir = ::CreateFile(path, FILE_LIST_DIRECTORY, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, NULL);

FILE_NOTIFY_INFORMATION returnData[1024];
DWORD returnDataSize = 0;                   

while(ReadDirectoryChangesW(hDir, returnData, sizeof(returnData), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_LAST_WRITE, &returnDataSize, NULL, NULL))
{
    ...
}

ReadDirectoryChangesW blocks the thread until a file changes occurs. Is there any way to stop/force return from this function?

Upvotes: 5

Views: 3594

Answers (4)

MSalters
MSalters

Reputation: 179779

From your description, it sounds like CancelIoEx should do the trick. Obviously, you need another thread for that, since you're now calling it synchronously. That blocks the calling thread, so you can't do anyting from that thread, not even stop.

Upvotes: 6

Martin James
Martin James

Reputation: 24847

If you want the blocking call to return from another thread, change something that will make the call return - create a temporary file, perhaps.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

You need to call this API function in its asynchronous mode of operation. You achieve this, as with many other file APIs, by passing an OVERLAPPED struct to the API call.

When you operate asynchronously the function will return immediately and it's up to you when you choose to collect the results. You can test whether or not the function is ready to supply results, you can opt to be notified that the API has results available, you can cancel the pending I/O, and you can choose to block until results are available. There is an awful lot of flexibility and naturally the API is more complex to use in asynchronous mode.

There is lots of information on MSDN about overlapped I/O. Start here: Synchronization and Overlapped Input and Output.

Upvotes: 1

Kiril
Kiril

Reputation: 40345

I think you need to take a look at this blog post: http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html

It's a lengthy post, but it's very informative and it talks about all the issues associated with this method.

Upvotes: 1

Related Questions