This blog has moved!

Check out www.CodeBetter.com/blogs/grant.killian

<August 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456


Navigation

Professional Props...

Extracurricular Props...

Subscriptions

Article Categories



Async Exception Handling

Before I went away on holiday, a few people asked me about exception handing for asynchronous methods -- possibly because they were experimenting with the various async examples I had blogged about.  While I don't have a lot of time (I'm supposed to be writing a lot of code documentation for a project I'm on --yuck), I need a break so let me share the error handling mechanism I usually employ for asynchrounous methods.  It's nothing more sophisticated than adding an "ErrorText" member variable to the custom eventargs class; I pass types of this eventargs class to my callback function and, therefore, the callback function can examine the value of the property to see if there is any error text to deal with.  This class serves as the messenger between the threads of execution.

My custom eventargs class looks something like this (I've omitted the propery sets and gets and some other code for brevity):
 public class StatusEventArgs : EventArgs
 {
  public string ErrorText;
  public StatusEventArgs()
  {
   this.ErrorText = "";
  }
 }

When an exception is raised, I simply assign a value to the ErrorText property in the catch portion of my try-catch block (e.ErrorText = ex.ToString() ) and then I use the callback method I discussed earlier to communicate the condition back to the client.

Nothing too fancy, I treat Exceptions in the async component like state in any other business object.  There's many angles you could take with this.  You could expose a generic Exception object from the StatusEventArgs class instead of the string variable and use e.TheExceptionObject = ex; you'd have access to the full exception type generated by the asynchronous method this way.  I know some people who prefer using integer values to communicate Exception severity to the client, and this model would certainly accomodate that.  Others may want to use a simple boolean for success or failure, and again the approach I present will suffice.  The point is, extend the object you pass back and forth for asynchronous communications to include any error information you may be interested in.

Happy .Netting!

posted on Wednesday, September 24, 2003 12:05 PM by grant.killian





Powered by Dot Net Junkies, by Telligent Systems