2
\$\begingroup\$

I have an interface, implemented by a service, that I inject here and there in my codebase. I would like to give the opportunity to use either the normal method or its async equivalent.

public interface IServiceDoStuff
{
    void DoSomeHeavyWork();
    Task DoSomeHeavyWorkAsync();     
}

In my implementation I just do it like this

public class Service: IServiceDoStuff
{
    public void DoSomeHeavyWork(){ ... }

    public Task DoSomeHeavyWorkAsync()
    {
        return Task.Run(() => { DoSomeHeavyWork();});
    }
}

So my consumers just go

await injectedService.DoSomeHeavyWorkAsync();

My question is simply : is that a correct way to offer those two alternatives ?

Tasks, async and await have been giving me headaches forever, as it has always been one of the most obscure .NET features I work with. I can never feel confident about the code I write using those features.

\$\endgroup\$
2
2
\$\begingroup\$

If your implementation does not create interrupts of some sort there is no point in making it async. If the consumer does not want to wait for your code to execute its better to let them control that and execute your code seperate from the main thread.

Edit: if the interface and implementation are shipped seperate or if its possible someone will replace default none async implementation with a async implementation. Than it could be a good practice to make the interface Async and in your default implementation return Task.FromResult or Task.CompletedTask.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.