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 ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.