3

There is this controller file, SecretAuthController.cs

    public class SecretAuthController : Controller 
    {
          public ActionResult Auth()
          {
               //library method whose signature recently changed to async

              return ProcessTelemetry();
          }        
    }

So, my colleague changed this code to

        public class SecretAuthController : MyBaseController
        {
              public Async Task<ActionResult> Auth()
              {
                   //library method whose signature recently changed to async                  
                   await MyLib.GetTaskDetails(Id);
                   return ProcessTelemetry();
              }        
        }

In this process, they also changed all other controller methods signature too to use 1async.

So, some methods look like

     public Async Task<ActionResult> ExFooTest()
     {
           //There is no awaitable call here
           //normally returns.
     }

Few doubts regarding this:

  1. If there is no awaitable call, is it wise to change the method signature to use async ?
  2. Is it a general rule, that if we want to change one action method signature to use async, should we need to change all the action method signature ? (Assume they don't await)

2 Answers2

5

If there is no awaitable call, is it wise to change the method signature to use async ?

No, you shouldn't. I think Visual Studio even gives you a hint about it:

This async method lacks 'await' operators and will run synchronously

async was introduced to make it easier to handle I/O, DB and other high latency operations. That doesn't mean that it should be used all the time. It still produces some overhead, and it is more likely to give you a negative performance impact if used when not needed. Only use async when you actually await something. And when you do you should do it all the way.

Now we talk about Controllers, which often is the entry point of an application. But let's look at situation from a wider perspective. What if you have a repository that is used by a couple of other classes which for some reasons cannot use await. If that repository made all it's methods async it would simply cause all the other classes to lock the thread while awaiting the operation.

Instead you should think about what you have to gain from using async. Can the consumer await it and will it improve performance? If it's async all the way, then yes. Otherwise, probably no.

Further reading:

Async/Await - Best Practices in Asynchronous Programming

Why shouldn't all functions be async by default?

Should I worry about "This async method lacks 'await' operators and will run synchronously" warning

Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74
1

You only need to make function async if there is an awaitable/async functionality in it. There is no need or a requirement to change all actions to async.

To Ka
  • 640
  • 8
  • 24