0

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.

2
  • how about return await Task.Run(() => //your synchronous code geos here)); Commented Jan 23, 2019 at 4:31
  • 4
    Parallel Async Task you show no such things. also async doesn't make anything faster, its a scalability feature which indirectly could be a performance boost, however for a small site probably not Commented Jan 23, 2019 at 4:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is parallel.for going to boost it?
@PrawnHongs no because each iteration depends on the last this is not easy thing to break up in to workloads

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.