Friday, December 17, 2010

[Visual C# 5.0] Asynchronous Programming Exception Handling

In my last posts I showed you the new features of C# 5.0 concerning asynchronous programming based on the CTP of October. In this article I am going to focus on exception handling in such an asynchronous environment.

So how would you add exception handling to something that is executed asynchronously? Well in C# 4.0 this was very difficult to achieve. In C# 5.0 it is much more straightforward because you just have to wrap the asynchronous function call with a standard try/catch block.

Adding Asynchronous Exception Handling

Lets take the asynchronous function call which I introduced last time and add some exception handling by wrapping it as explained with a standard try/catch block.

AsyncCSharpe5Exceptions_1

Additionally I added code to throw a simulated exception within the function that calculates the factorials. We will then be able to analyze what happens when this function throws an exception.

AsyncCSharpe5Exceptions_2

When executing the application we see that everything is working correctly. The exception is caught and we may look in detail what properties values it contains.

AsyncCSharpe5Exceptions_3 

The CTP added some new exception language features that you can now see in action. Looking at the exception details and the stack trace you may note that the Source is the AsyncCtpLibrary and that the TargetSite/ReflectedType is System.Runtime.CompilerServices.TaskAwaiter.

AsyncCSharpe5Exceptions_4

AsyncCSharpe5Exceptions_5

Conclusion

You see that the CTP adds features that greatly simply asynchronous exception handling. Exceptions get more comprehensible and easier to exploit in such an environment. Developers do not have to learn any new methods or use complex workarounds to handle exceptions correctly. There is no difference for them between synchronous and asynchronous code which is a great help!


Share/Save/Bookmark

No comments: