Home > Back-end >  Dealing with async function doing sync work
Dealing with async function doing sync work

Time:09-17

So I have an interface that defines some function including this

Task DoWork();

The problem is that some of the class implementing this interface does not need to do work asynchronously so my current solution is returning Task.CompletedTask after doing some synchronous work.

The question is: Am I doing it in a wrong way, I feel that having an async function doing sync work is kind of wrong

CodePudding user response:

It may feel wrong - it may even BE wrong, but the wrongness is not on your side.

If a method is defined as returning a Task, then this is either you implementing a special case of the method that in this particular case does not have to be async... or it is simply that the definition of the method is wrong and it should not return a Task.

THIS is the semantical challenge. But you implementing it as Task.CompletedTask is just you following in this case the semantics as lined out, as per the C# specifications, actually.

With a concrete example we could discuss whether the method SHOULD return a Task or not... but generally: This happens. Why you think Task.CompletedTask exists?

CodePudding user response:

If your usage of the interface requires the operation be async-friendly, then no it's not wrong. Task.CompletedTask was made available as part of the C# language for a reason. It's important to reflect on usages of it and whether you're really doing something wrong or just conforming to the contract defined by your interface, which you seem to be doing by asking this question.

If you find yourself repeating this pattern often in your interface implementations then perhaps that's an opportunity to rethink your architecture: why you have interfaces that sometimes run synchronously and sometimes run asynchronously and how you can better design a system that handles a concrete implementation that needs to do work asynchronously versus a concrete implementation that doesn't need to run asynchronously.

  • Related