Web service calls have an easy way to define a timeout handler. (After the actual web service method's parameters, it's the second parameter to the call.)
For async postbacks (UpdatePanels), it's not quite as simple. You need to handle the EndRequest event on the PageRequestManager. The first parameter to your event handler is a reference to the PageRequestManager itself, but the second parameter is an instance of the EndRequestEventArgs class. When an error occurs, you can use get_error() to take a look at what happened. Here's some code that uses an EndRequest event handler to check for a timeout error and handle it:
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void slow_postback(object sender, EventArgs e)
{
// ten seconds is overkill... we timeout after one second (see ScriptManager below)
System.Threading.Thread.Sleep(10000);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Handling an async postback timeout</title>
</head>
<body>
<form id="form1" runat="server">
<!-- This sets the timeout on async postbacks (i.e. UpdatePanel refreshes) to one second -->
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="1" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Fast postback - no timeout" /> <br />
<asp:Button ID="Button2" runat="server" Text="Slow postback - times out after one second" OnClick="slow_postback" /> <br />
Last updated: <%= DateTime.Now %>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
if (args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException') {
alert('Caught a timeout!');
// remember to set errorHandled = true to keep from getting a popup from the AJAX library itself
args.set_errorHandled(true);
}
});
</script>
</html>
That's it! Maybe not immediately obvious, but also not that difficult once you've seen it done. Also note that I'm explicitly setting a one-second timeout for the purposes of this sample. You probably want a longer timeout. (The default is ninety seconds.)