Starfleet Security
Starfleet Security

Reputation: 1843

Should I be using async/await in WEB API on the server?

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?

Upvotes: 1

Views: 2487

Answers (1)

Mandalorian
Mandalorian

Reputation: 154

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).

Upvotes: 2

Related Questions