How to use timeout property of the proxy class in C#

In some cases for your web-page client, which consume a web service, you need to specify the maximum amount of time it has to wait. The article How to create an ASP.NET web-page client for a web service in C# does not cover this area. By default the timeout is 100,000 milliseconds (10 seconds).

You can specify different timeout by using the Timeout property. You should combine the property with error handling mechanisms, because if the timeout period expires without a response, an exception should be thrown, giving you the option to notify the user about the problem.  The next code lines show how you can rewrite the ASP.NET web-page client to use a timeout of five seconds:

 

private void cmdGetData_Click(object sender, System.EventArgs e)

{

// Create the proxy.

BooksService proxy = new BooksService();

// This timeout will apply to all web service method calls.

proxy.Timeout = 5000; // 5,000 milliseconds are 5 seconds.

DataSet ds = null;

 

try

{

// Call the web service and get the results.

ds = proxy.GetBooks();

}

catch (System.Net.WebException err)

{

if (err.Status == WebExceptionStatus.Timeout)

{

lblResult.Text = “Web service timed out after 5 seconds.”;

}

else

{

lblResult.Text = “Another type of problem occurred.”;

}

}

 

// Bind the results.

if (ds != null)

{

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

}

}

 

You can also set the timeout to -1 to indicate that your client will wait as long as it takes. This will make your web application unacceptably slow if you attempt to perform a number of operations with an unresponsive web service.