<%@ Page %>
Handling Timeouts in Web Services
Introduction
While developing web applications you should also consider factors like network downtime and server crashes. The same applies to developing web services. When you call a method from your client by default it waits infinitely for the response. This means if server hosting the web service is down then you are bound to get error after a long wait. In this article we will how to deal with such timeouts in web services.
Web Service Proxy
Before consuming a web service from .NET clients you will typically create a web service proxy for the web service. The proxy class so generated has a property called Timeout that can be used to set the timeout value for the web service. Following code in C# shows how to set the property:
localhost.Service1 proxy=new localhost.Service1();
proxy.Timeout=2000;
Note that
- localhost is the namespace of the proxy class.
- Service1 is the web service under consideration
- The Timeout property is set to number of milliseconds for which the client will wait for response from the web service. If the web service is unable to respond in that much time an exception will be thrown.
- If you set the Timeout property to -1 then the web service proxy will wait infinitely for the response to come.
Connecting with a backup web service in case of failure
You can also trap the timeouts and connect with some backup server where the same web service is hosted. Following code shows how:
localhost.Service1 proxy=new localhost.Service1();
proxy.Timeout=2000;
try
{
proxy.SomeMethod();
}
catch
{
proxy.Url="http://www.anotherserver.com/service2.asmx";
proxy.SomeMethod();
}
Here
- We have created instance of web service proxy as usual
- We then set time out value to 2000
- We then put the call to the web method (SomeMethod) in try..catch block
- If the web method call times out we point the proxy to the backup web service and call the same method
Note that both the web service must be identical.
I hope you must have found the article useful.
Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go
here. More details about his Ajapa Japa and Shambhavi Mudra online course are available
here.