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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With