Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "Async" suffix required in the name of an async ASP.NET MVC 4 action?

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?

like image 847
Marius Schulz Avatar asked Feb 01 '13 18:02

Marius Schulz


People also ask

Should I use async suffix?

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.

How do you call async method in MVC action?

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.

What is async keyword in C#?

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.

What is async controller in MVC why one should use it?

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.


2 Answers

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.

like image 133
Tom Tregenna Avatar answered Sep 17 '22 15:09

Tom Tregenna


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

like image 33
Travis J Avatar answered Sep 21 '22 15:09

Travis J