views:

240

answers:

3

I've read the documentation for ReadDirectoryChangesW() and also seen the CDirectoryChangeWatcher project, but neither say why one would want to call it asynchronously. I understand that the current thread will not block, but, at least for the CDirectoryChangeWatcher code that uses a completion port, when it calls GetQueuedCompletionStatus(), that thread blocks anyway (if there are no changes).

So if I call ReadDirectoryChangesW() synchronously in a separate thread in the first place that I don't care if it blocks, why would I ever want to call ReadDirectoryChangesW() asynchronously?

+1  A: 

You would call ReadDirectoryChangesW such that it returns its results asynchronously if you ever needed the calling thread to not block. A tautology, but the truth.

Candidates for such threads: the UI thread & any thread that is solely responsible for servicing a number of resources (Sockets, any sort of IPC, independent files, etc.).

Not being familiar with the project, I'd guess the CDirectoryChangeWatcher doesn't care if its worker thread blocks. Generally, that's the nature of worker threads.

Kevin Montrose
So you're saying there is no good reason? Again, as I said originally, if I cared if the current thread blocks, I would create a separate thread that I don't care if it blocks.
Paul J. Lucas
Creating a thread is not always an (good) option, and an API is going to try and service as many users as possible thus the async option.
Kevin Montrose
+2  A: 

When you call it asynchronously, you have more control over which thread does the waiting. It also allows you to have a single thread wait for multiple things, such as a directory change, an event, and a message. Finally, even if you're doing the waiting in the same thread that set up the watch in the first place, it gives you control over how long you're willing to wait. GetQueuedCompletionStatus has a timeout parameter that ReadDirectoryChangesW doesn't offer by itself.

Rob Kennedy
A: 

I tried using ReadDirectoryChanges in a worker thread synchronously, and guess what, it blocked so that the thread wouldn't exit by itself at the program exit. So if you don't want to use evil things like TerminateThread, you should use asynchronous calls.

Alex Jenter
If the thread didn't stop, then you hadn't really told the OS that your process was finished. `ExitProcess` terminates all threads.
Rob Kennedy
From MSDN:"How Processes are Terminated:A process executes until one of the following events occurs:- Any thread of the process calls the ExitProcess function. ...Do not terminate a process unless its threads are in known states. If a thread is waiting on a kernel object, it will not be terminated until the wait has completed. This can cause the application to hang."
Alex Jenter