简体   繁体   中英

Calling an async method from the browser

From my understanding when we use await and the awaited task is not yet completed then the execution returns to caller . It works fine in server side(calling the async method from server side method itself). But what happends when I call from UI to an async method.

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 tested with the above API from browser like

http://localhost:port/Test

, but I got response only after 5 sec in my UI. Am I thinking it wrongly?

Am I thinking it wrongly?

Yes. async-await does not change the nature of the HTTP protocol, which is of type request-response. When using async-await inside an ASP.NET controller, using an async method will not yield a response to the caller, it would only yield the requests thread back to the threadpool.

But if this is true, then using async method having a single await in controller side is not useful. right? because it took the same time of synchronous call

Async shines when you need scalability . It isn't about "yield this response as fast as possible", it's about being able to handle a large amount of requests without exhausting the thread-pool. Once the thread starts executing IO work, instead of being blocked, it is returned. Thus, able to serve more requests.

Async by itself does not make anything "go faster", which is a conception I see people thinking alot. If you're not going to be hitting your web service with many concurrent requests, you're most likely not going to be seeing any benefit from using it. As @Scott points out, an async method has a slight overhead as it generates a state machine behind the scenes.

async/await allow the thread to go off servicing other requests while there is that idle 5 seconds, but ultimately everything in GetMyCollectionAsync has to complete before a response is sent to the client.

So I'd expect your code to take 5 seconds and return all 3 strings in the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM