Given the following ASP.NET MVC 4 controller action:
public async Task<ActionResult> FooAsync()
{
using (var httpClient = new HttpClient())
{
var responseMessage = await httpClient.GetAsync("http://stackoverflow.com");
string response = await responseMessage.Content.ReadAsStringAsync();
return Content(response);
}
}
Do I need to put the "Async" suffix in FooAsync for the action to be run asynchronously?
You should add suffix Async to a method which, in some cases (not necessarily all), doesn't return a value but rather returns a wrapper around an ongoing operation.
STEP 01 Create new MVC Application project, named as "Async". In the File menu, click New Project. In the "New Project" dialog box, under Project types, expand Visual C#, and then click "Web". In the Name box, type "Async", then click on Ok.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action.
Although it's not a requirement, I like to follow convention and see the "...Async" suffix on my asynchronous methods, so I tend to use the ActionName
attribute to decorate the controller actions with the non-async name, this way you can have your cake and eat it too :)
[ActionName("Index")]
public async Task<ActionResult> IndexAsync()
{
return View();
}
I find this works just fine.
No, this is not a requirement.
By convention, you append "Async" to the names of methods that have an Async or async modifier.
You can ignore the convention where an event, base class, or interface contract suggests a different name. For example, you shouldn’t rename common event handlers, such as Button1_Click.
source: MSDN: Asynchronous Programming with Async and Await C# -> Naming Convetions
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