Things not to do, Part 3: Don't call CreateFile on your Windows message pump thread.

Sometimes it’s not a big deal, but there are some situations where it’s disastrous to call CreateFile on a message pump thread.

The problem occurs because CreateFile might take a long time to complete. Conceivably it could actually take HOURS (although that is highly unlikely). And if you’re calling CreateFile on your message pump thread, you’re not pumping messages (since CreateFile is synchronous). Which means your app freezes and you get the dreaded “(not responding)” on your window if the user attempts to interact with your app.

Why would it take so long? Well, what happens if the file’s located on slow media? Like a floppy – remember floppy disks? They can spend several seconds spinning up, especially if the floppy is newly inserted in the disk drive. 

Another even more common cause is if the file in question is located on a network drive – the first thing that happens when you’re opening a networked file is a DNS lookup which can take several seconds to complete. Then you need to contact the file server, which in turn has to authenticate the user, and then process the open, all of which may also take several seconds to complete. 

If the file being opened is a message mode named pipe, you might block until an instance of the pipe becomes available on the server end, which could conceivably be hours (whenever the current named pipe clients disconnect).

 

Bottom line: Don’t do ANY file I/O on your message pump threads; offload them to worker threads so you can make your app responsive.