vendredi 26 juin 2020

C# async decorator best practices

I have simple asynchronous service, which I need to decorate.

What is the best practice when you decorate an asynchronous method?

  • should I use async/await in the decorator? Example1

  • should I leave it as Task<> and use await only on the original caller?

Example

public interface IService
{
    Task<bool> GetStatusAsync();
}

public class Example1 : IService
{
    private readonly IService _decorated;
    public Example1(IService decorated)
    {
        _decorated = decorated;
    }

    public async Task<bool> GetStatusAsync()
    {
        // extra code

        return await _decorated.GetStatusAsync();
    }
}

public class Example2 : IService
{
    private readonly IService _decorated;
    public Example2(IService decorated)
    {
        _decorated = decorated;
    }

    public Task<bool> GetStatusAsync()
    {
        // extra code

        return _decorated.GetStatusAsync();
    }
}

Aucun commentaire:

Enregistrer un commentaire