winapi – Asynchronous read / write to Win32API file

Question:

Hello.

Ran into the following problem. I need to read the first n lines from the files in the directory and enter them into another file, and this must be done using the Win32 API (CreateFile, ReadFile, WriteFile и т.д.) functions Win32 API (CreateFile, ReadFile, WriteFile и т.д.) . It was not difficult to do all this synchronously, but doing it asynchronously (which is exactly what I need to do) does not work. I pass the Overlapped file attribute to the penultimate parameter of the CreateFile (flagsAndAttributes) function CreateFile (flagsAndAttributes) , and the ReadFile function immediately starts returning false . How to organize read-write, I can not understand. Help me please. I write, generally speaking, in C #, but C ++ code will help too. The main Win32Api is the use of Win32Api functions and asynchronous work.

Answer:

Most likely, the problem is that by default .NET threads run in a multi-threaded apartment, and a single-threaded one is needed to call WinApi functions. Try to mark the methods you use to run asynchronously with STAThread , or call SetApartmentState on the thread when creating a thread. True, any asynchronous operation works through a ThreadPool , which needs a multi-threaded apartment. So BeginDo - EndDo about the BeginDo - EndDo for calling WinAPI functions asynchronously.

Scroll to Top