samedi 13 janvier 2024

Writing an async version of a method in a DRY fashion?

The documentation of System.IO.Stream specifies that, when deriving from it, at most, only the Read method needs to be implemented.

This automatically enables the use of ReadAsync method in the derived type, i.e. you get asynchronous reading for free.

Looking at how it is implemented, it is pretty involved. There is a custom class (ReadWriteTask) deriving from Task<int> which is responsible for the asynchronous reading.

A naive approach for one to avoid DRY could be the following:

public abstract class Reader
{
    public abstract int Length { get; }

    public bool TryRead(Stream stream, byte[] buffer)
    {
        if (stream.Length - stream.Position < Length)
        {
            return false;
        }

        stream.ReadExactly(buffer);

        // do some special, lengthy stuff

        return true;
    }

    public async Task<bool> TryReadAsync(Stream stream, byte[] buffer)
    {
        return await Task.Run(() => TryRead(stream, buffer)).ConfigureAwait(false);
    }
}

However, after looking at their implementation, I have the feeling that the above approach may be wrong/inefficient.

Can you suggest a pattern to tackle this problem?

Aucun commentaire:

Enregistrer un commentaire