
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Handling Exceptions Thrown from an Asynchronous Delegate
|
421
System.Threading.Thread.Sleep(100);
Console.Write('.');
}
Console.WriteLine("Finished Polling");
// Call the EndInvoke method of the async delegate.
try
{
int RetVal = MI.EndInvoke(AR);
Console.WriteLine("RetVal: " + RetVal);
}
catch (Exception e)
{
Console.WriteLine(e.ToString( ));
}
}
}
The following code defines the AsyncInvoke delegate and the asynchronously invoked
static method
TestAsyncInvoke.Method1:
public delegate int AsyncInvoke( );
public class TestAsyncInvoke
{
public static int Method1( )
{
throw (new Exception("Method1")); // Simulate an exception being thrown.
}
}
Discussion
If the code in the PollAsyncDelegate method did not contain a call to the delegate’s
EndInvoke method, the exception thrown in Method1 either would simply be dis-
carded and never caught or, if the application had the top, level exception handlers
wired up (Recipes 7.10 and 7.20) it would be caught. If
EndInvoke is called, then this
exception would occur when
EndInvoke is called and could be caught there. This
behavior is by design; for all unhandled exceptions that occur within the thread, the
thread immediately returns to the thread pool and the exception is lost.
If a method that was called asynchronously through a delegate throws an exception, ...