Prawn Hongs
Prawn Hongs

Reputation: 451

How to use async , parallel task in the controller class - Web API?

I am trying to make my REST APIs more responsive by using Async or Parallel Async Task approach. Here is my code which is synchronous in nature. I have no idea on how can I make it more responsive by using Async or Parallel TPL.

 [HttpGet]
        public async Task<string> Get([FromQuery(Name = "number")] long number)
        {

This is original Synchronous code -

[HttpGet]
    public string Get([FromQuery(Name = "number")] long number)
    {
        ulong lastItem = (ulong)number;
        ulong fact = 1;
        for (ulong i = 1; i < lastItem; i++)
        {
            fact = fact * i;
        }
        return fact.ToString();
    }

I want to make this code faster when using REST API - calls. My plan is to use Task Parallel but I am not sure how can I do so? Once I can do I will check if the performance is improved or not.

Upvotes: 0

Views: 227

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

async doesn't make anything faster, it's a scalability feature which indirectly could be a performance boost, however for a small site probably not.

In regards to your question, there is no point making this call async, it's a CPU workload, it will not use an IO Completion port, and will use a threadpool thread and block it (for lack of a better word) no matter which way you do it. In short, there is no IO Bound operation for async to work its true magic.

Sure you could do this:

return await Task.Run(() =>
{
   ulong lastItem = (ulong)number;
   ulong fact = 1;

   for (ulong i = 1; i < lastItem; i++)
   {
      fact = fact * i;
   }

   return fact;
});

But what's happening? You are just freeing up a thread pool thread, to use/switching to another, then back... there is little to no benefit.

IMO, you are just better leave it as it is.

Upvotes: 3

Related Questions