Hello.

I ran into the next problem. I need to read the first n lines from the files in the directory and put them into another file, and this should 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 to do it asynchronously (and that's exactly what I need) does not work. In the penultimate parameter of the CreateFile (flagsAndAttributes) function CreateFile (flagsAndAttributes) I pass the Overlapped file attribute, and the ReadFile function immediately starts returning false . How to organize a read-write, I can not understand. Help me please. I write, generally speaking, in C #, but the code in C ++ also helps. The main Win32Api is using Win32Api functions and asynchronous operation.

  • And where does the requirement to use bare WinAPI come from? - VladD
  • 2
    No, no, wait. Who set you this task? What is the motivation? Asynchronous reading in C #, let's say, just like 5 cents: using (var in = File.OpenText (infile)) using (var out = File.CreateText (outfile)) for (int i = 0; i <N; i ++) { var line = await in.ReadLineAsync (in); await out.WriteLineAsync (out); } - VladD
  • one
    A strange question, in order to help a person, it is necessary to know who set the task for him? - psixdev
  • one
    @Expert: My text is not quite on the topic of the question: TS asks how to do C / WinAPI, and I give a high-level example in C #. So my text is more of a comment. - VladD
  • one
    I vote for the closure of this issue because it is a learning task, which for the author is no longer relevant for a long time, but for some reason the community doesn’t have a desire to do learning tasks. - Pavel Mayorov

1 answer 1

Most likely, the problem is that, by default, .NET streams work in a multi-threaded apartment, and to call WinApi functions, you need a single-threaded one. Try marking the methods you use to start STAThread STAThread , or call SetApartmentState on the flow when creating a flow. True, every asynchronous works through ThreadPool , which needs a multi-threaded apartment. Therefore, the syntax BeginDo - EndDo for asynchronous call WinAPI functions should be forgotten.

  • No, it can not be. Any library function will call WinAPI sooner or later, that is, if STA would be necessary for WinAPI, then it would be impossible to access files from the MTA. - VladD
  • Well, somehow no pinvoke worked for me in MTAThread at all. At least, I would definitely dig in this direction. - Modus