Section 7.4. Asynchronous Error Handling


7.4. Asynchronous Error Handling

Output parameters and return values aren't the only elements unavailable at the time an asynchronous call is dispatched: exceptions are missing as well. After calling BeginInvoke( ), control returns to the client, but it may be some time before the asynchronous method encounters an error and throws an exception, and it may be some time after that before the client actually calls EndInvoke( ). .NET must therefore provide some way for the client to know that an exception was thrown and be allowed to handle it. The .NET solution is straightforward: when the asynchronous method throws an exception, .NET catches it, and when the client calls EndInvoke( ) .NET re-throws that exception object, letting the client handle the exception. If a callback method is provided, .NET calls the callback method immediately after the exception is thrown on the object side. For example, suppose the Calculator class has a Divide( ) method, defined as:

     public class Calculator     {        public int Divide(int argument1,int argument2)        {           return argument1/argument2;        }        //Other methods     }

Divide( ) throws a DivideByZeroException if the denominator (argument2) passed in is zero. Example 7-11 demonstrates how you might handle this error.

Example 7-11. Asynchronous error handling
 public class CalculatorClient {    public void AsyncDivide(  )    {       Calculator calculator = new Calculator(  );       BinaryOperation oppDel = calculator.Divide;       oppDel.BeginInvoke(2,0,OnMethodCompletion,null);    }    void OnMethodCompletion(IAsyncResult asyncResult)    {       AsyncResult resultObj = (AsyncResult)asyncResult;       Debug.Assert(resultObj.EndInvokeCalled == false);       BinaryOperation oppDel  = (BinaryOperation)resultObj.AsyncDelegate;       try       {          int result = 0;          result = oppDel.EndInvoke(asyncResult);          Trace.WriteLine("Operation returned " + result);       }       catch(DivideByZeroException exception)       {          Trace.WriteLine(exception.Message);       }    } }

When you use a completion callback method, you must provide for error handling in the callback. If the call to EndInvoke( ) results in an exception and no error handling is in place, the exception will terminate your application.




Programming. NET Components
Programming .NET Components, 2nd Edition
ISBN: 0596102070
EAN: 2147483647
Year: 2003
Pages: 145
Authors: Juval Lowy

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net