mo.notono.us

Thursday, April 15, 2004

Handling WebService Exceptions When Invoking a Webmethod Asynchronously

From the "duh, of course, but I forgot it" department: When catching a SoapException thrown by a WebMethod that you called asyncronously, you have to pass the exception back to the UI thread through a delegate if you want to, say, display a message to the user:
/// <summary>A delegate used to pass the data from the asynch webservice call back to the UI thread</summary>
private delegate void SaveDel(ContactDS cDS);
/// <summary>Delegate used to pass any exception back to the UI thread</summary>
private delegate void AsynchErrorDel(Exception exc);

/// <summary>
/// Call-back method running on the Asynchronous WS thread.
/// </summary>
/// <param name="ar">Represents the status of the asynchronous operation</param>
private void SaveContact(IAsyncResult ar)
{
	try
	{
		//Get the contact record count from the EndInvoke WS method
		ContactDS cDS = new ContactBll().EndSaveContact(ar);
		//Pass the record count to the UI thread by invoking the UpdateStatus method through the SaveDel delegate
		this.Invoke(new SaveDel(UpdateStatus), new object[]{cDS});
	}
	catch (Exception exc)
	{
		//if something went wrog during the call, pass the exception back to the UI thread
		this.Invoke(new AsynchErrorDel(HandleAsynchError), new object[]{exc});
	}
}
This really is no different from any other asynch call - you shouldn't update the UI from a background worker thread.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home