1

So I'm writing a WEB API with .NET 5 and I started with something like this to get my data:

    public ProfileModel Get(string email)
    {
        using (JobsDB data = new JobsDB())
        {
            return data.Profiles.Where(x => x.Email.ToUpper() == email.ToUpper()).FirstOrDefault();
        }
    }

But I just ran across an article that made me think I should be writing it using async/await like this:

    public async Task<ProfileModel> Get(string email)
    {
        using (JobsDB data = new JobsDB())
        {
            return await data.Profiles.Where(x => x.Email.ToUpper() == email.ToUpper()).FirstOrDefaultAsync();
        }
    }

Now I realize that when the client application calls the WEB API, they will do so in an asynchronous manner (in their JavaScript code), so I always thought that the WEB API itself didn't have to use asynchronous methods. So is there a true advantage to using async/await in the WEB API itself? Is it considered "best practices" to do so anyway?

Starfleet Security
  • 1,813
  • 3
  • 25
  • 31
  • There are tons of blogs out there that talks about when to use asynchronous programming. What's important is not to mistake all asynchronous calls as a new thread call. Common areas where you want to do async-await is I/O, database operations and etc. It's better for you to look at guides and blogs for this info instead of StackOverflow which is more about specific coding problems. – jegtugado Mar 30 '21 at 08:21

1 Answers1

1

Yes, it is a best practice to make your API Endpoints asynchronous in according to this Microsoft's article.

An asynchronous operations allows to "optimize" amount of threads involved in request handling by involving the same thread to process another request, while the previous is under await (more details here).

Also, you can read this article to understand the difference between return await Task and return Task (there is a difference which is important to know).

Mandalorian
  • 134
  • 1
  • 3