Calling the async method from the browser

From my understanding , when we use await and the awaited task has not completed yet, execution falls back to the caller . It works fine on the server side (calling the async method from the server side method itself). But what happens when I call the asynchronous access method from the UI.

public class TestController : ApiController
{
        IList<string> lstString = new List<string>();
        public async Task<IList<string>> GetMyCollectionAsync()
        {
            lstString.Add("First");
            string secString = await GetSecondString(); // I am expecting a response back to UI from here.
            lstString.Add(secString);
            lstString.Add("Third");
            return lstString;
        }

        private async Task<string> GetSecondString()
        {
            await Task.Delay(5000);
            return "Second after await";
        }
}

      

I have tested the above API from a browser like

http: // localhost: port / Test

but I only got a response after 5 seconds in my interface. I think it's wrong?

+3


source to share


2 answers


I think it's wrong?

Yes. async-await

does not change the nature of the HTTP protocol, which is of the request-response type. When used async-await

inside an ASP.NET controller, using the async method will not respond to the caller, it will only return a thread of requests to the threadpool.

But if so, then using an async method that has a single expectation on the controller side is not useful. right? because it took a synchronous call time



Async shines when you need scalability . It is not about "getting this answer as fast as possible", but about being able to handle a large number of requests without exhausting the thread pool. When a thread starts doing work with IO, instead of being blocked, it returns. This way more requests can be served.

Async by itself doesn't make anything "faster", which is a concept I see people think a lot about. Unless you're going to push to your web service with many concurrent requests, you most likely won't see any benefit from using it. As @Scott points out, the async method has a small overhead since it generates a state machine behind the scenes.

+6


source


async / await allows a thread to disconnect from serving other requests while this idle for 5 seconds, but eventually everything in GetMyCollectionAsync must complete before sending a response to the client.



So, I expect your code to take 5 seconds and return all 3 lines in the response.

+1


source







All Articles