Sunday, October 21, 2012

Should web services be called asynchronously from ASP.NET page?

What if you have a thread that makes an HTTP or SOAP request to another server and takes a long time, should you switch threads?

Yes! You can perform the HTTP or SOAP request asynchronously, so that once the "send" has occurred, you can unwind the current thread and not use any threads until there is an I/O completion for the "receive". Between the "send" and the "receive", the remote server is busy, so locally you don't need to be blocking on a thread, but instead make use of the asynchronous APIs provided in .NET Framework so that you can unwind and be notified upon completion.  Again, it only makes sense to switch threads if the benefit from doing so out weights the cost of the switch.

However, just calling web service asynchronously does not help?

If you want work to be performed asynchronously—truly asynchronously, as in the current thread unwinds and execution of the request resumes only if and when your work completes—then you must run inside a module or handler that is asynchronous. If you do not use an asynchronous handler, the thread that ASP.NET initiated to handle incoming request will have to be blocked. So, even though you call web service asynchronously it really would not help in a true sense.

No comments: