Buda Gavril Buda Gavril - 16 days ago 6
C# Question

create asynchronous and synchronous methods for a repository

I have a repository with a method

Insert
that returns an
int
(the methods and types are not relevant here). I am thinking to create
synchronous
and
asynchronous
insert methods for this repository. For the
asynchronous
method is it a good practice to enclose the
synchronous
Insert
method in a
task
to avoid the code duplication?

Answer

No, this is not a good practice, as detailed by Microsoft's Stephen Toub here:

https://blogs.msdn.microsoft.com/pfxteam/2012/03/24/should-i-expose-asynchronous-wrappers-for-synchronous-methods/

... and by Stephen Cleary here:

http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html

Long story short, if all your method does is wrap a synchronous call in Task.Run, that's trivial and I'm sure the caller is perfectly capable of doing it themselves. There is no need to increase the surface area of your API unless you have a naturally asynchronous operation (or unless you know that in the future you'll be able to provide one, and therefore want the consumers to target the XxxAsync method from day one).

As a bonus, here's a real life example of async wrapper methods being removed from a popular library:

JSON.NET used to provide SerializeAsync and DeserializeAsync methods which were just wrappers around their synchronous counterparts using Task.Factory.StartNew. Those were eventually obsoleted as they don't add value to the API and were deemed a potential scalability issue. The full discussion which led to this change can be found here:

https://github.com/JamesNK/Newtonsoft.Json/issues/66

Comments