Buda Gavril Buda Gavril - 1 year ago 57
C# Question

create asynchronous and synchronous methods for a repository

I have a repository with a method

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

Answer Source

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


... and by Stephen Cleary here:


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:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download