Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should methods in an API that return Task end with Task or Async

If an API has a synchronous method T DoSomething<T>();, what is the naming convention for the corresponding asynchronous method if it returns Task<T>?

Task<T> DoSomethingTask<T>();    

or

Task<T> DoSomethingAsync<T>();

or something else?

like image 689
dillenmeister Avatar asked Feb 02 '12 18:02

dillenmeister


People also ask

Should async method return Task?

For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited. Any caller of such a method must continue to completion without waiting for the called async method to finish.

Should all methods be async?

If a method has no async operations inside it there's no benefit in making it async . You should only have async methods where you have an async operation (I/O, DB, etc.). If your application has a lot of these I/O methods and they spread throughout your code base, that's not a bad thing.

When would you use asynchronous actions?

Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.

Why you should avoid async void?

Async void methods can wreak havoc if the caller isn't expecting them to be async. When the return type is Task, the caller knows it's dealing with a future operation; when the return type is void, the caller might assume the method is complete by the time it returns.


2 Answers

If you are talking about an async or await method, then from MSDN:

By convention, the suffix "Async" is added to the names of methods that are modified by the Async or async modifier.

...

Exceptions to the convention can be made where an event, base class, or interface contract suggests a different name. For example, the names of common event handlers, such as button1_Click, are best not renamed.

like image 133
Adam Spicer Avatar answered Oct 07 '22 06:10

Adam Spicer


From what I've seen in C# 5 / .NET 4.5, the preferred name is DoSomethingTaskAsync or DoSomethingAsync

For example, the WebClient class in .NET 4.5 has methods like DownloadFileTaskAsync, because it already had a method named DownloadFileAsync, so I assume the use of TaskAsync over Async is to maintain backwards compatibility.

like image 42
Daniel Mann Avatar answered Oct 07 '22 07:10

Daniel Mann