Skip to Main Content
Programming .NET Components, 2nd Edition
book

Programming .NET Components, 2nd Edition

by Juval Lowy
July 2005
Intermediate to advanced content levelIntermediate to advanced
644 pages
17h
English
O'Reilly Media, Inc.
Content preview from Programming .NET Components, 2nd Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Windows Forms Programming in C#

Windows Forms Programming in C#

Chris Sells
Metaprogramming in .NET

Metaprogramming in .NET

Jason Bock, Kevin Hazzard
.NET Windows Forms in a Nutshell

.NET Windows Forms in a Nutshell

Ian Griffiths, Matthew Adams

Publisher Resources

ISBN: 0596102070Supplemental ContentErrata Page