0
votes

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?

1

1 Answers

3
votes

.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);