简体   繁体   中英

Is there any way for writing into a FileStream asynchronously with older .net framework version?

Async and await operators were introduced with C# 5 and .NET Framework 4.5.

My problem is that in order to use async i need .NET Framework 4.5 or higher but i'd like to be able to do the same thing (writing into a FileStream asynchronously) on previous .NET Framework versions as well.

Currently i have a static observer class with an eventhandler. This event handler tied to an event that gets invoked each time a certain class is created. This event will call the following function:

    static async void FileWriter(string path, string fileName, byte[] text)
    {
        byte[] encodedText = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(437), text);

        using (FileStream sourceStream = new FileStream(Path.Combine(path, fileName),
            FileMode.Append, FileAccess.Write, FileShare.None,
            bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        };
    }

Is there any alternatives to make it work with older .NET Framework versions?

.NET Framework has supported async I/O for a lot longer than C# has the async / await keywords. You can use the APM methods: Stream.BeginWrite , Stream.BeginRead , etc.

These aren't very friendly to use, though. The equivalent of your example would be:

byte[] encodedText = ...;
FileStream sourceStream = ...;

sourceStream.BeginWrite(encodedText, 0, encodedText.Length, res =>
{
   try
   {
      // result of Write op materializes here -- exception etc.
      sourceStream.EndWrite(res);
   }
   finally
   {
      sourceStream.Dispose();
   }
}, state: null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM