Easiest way to read/write a file asynchronously?
I am looking for a simple way to read/write a file asynchronously using Win API. What I had is mind is something like the asynchronous winsock API (WSAxxx) completion routines. However the file API doesn't seem to have those. Are they hidden somewhere?
Waiting on the overlapped events in a seperate thread adds thread开发者_JAVA技巧 management overhead, not to mention there either needs to be a thread-per-file, or the 64 objects problem needs to be faced. Completion ports is an overkill. Reading the file synchronously on a seperate thread is irrelevant.
Any suggestions?
CreateFile
and ReadFile
/WriteFile
functions support so-called 'overlapped' mode which is what you need. There' also ReadFileEx
/WriteFileEx
that work in async mode only.
In short, you need to open file with FILE_FLAG_OVERLAPPED
flag and pass OVERLAPPED
structure (and callback in case of xxxEx
operations) to file access functions.
Here's a sample class for using it.
I know that in .net it's possible. What I don't know is to which win32 functions it maps
As soon as you step into the async territory you should forget the word "easiest" Seriously, the easiest would be to use .NET's System.IO.FileStream with isAsync=true in constructor and BeginRead/EndRead methods.
精彩评论