async \ await and Exception Handling
async \ await and Exception Handling
this post will discuss how async / await is handling exceptions.

as we mention in previous post, about the async / await concept, await is all about continuation.
before .NET 4.5 parallel execution exceptions has to be handle in separate of the synchronic handling.
for example:
handling ThreadPool execution:
Code Snippet
- void Foo()
- {
- try
- {
- Console.WriteLine("Synchronic");
- ThreadPool.QueueUserWorkItem(state =>
- {
- try
- {
- Console.WriteLine("Parallel");
- }
- catch (Exception exAsync)
- {
- EventLog.WriteEntry("application", exAsync.ToString());
- }
- }, null);
- }
- catch (Exception ex)
- {
- EventLog.WriteEntry("application", ex.ToString());
- }
- }
as you can see we have to handle the parallel exception (line 12) in separate from the synchronic handling (line 18).
TPL has brought new option for handling parallel exception, now you can use ContinueWith with TaskContinuationOptions.OnlyOnFault (line 8).
but still you have to handle the parallel exception is in separate of the synchronic one:
Code Snippet
- void Foo()
- {
- try
- {
- Console.WriteLine("Synchronic");
- Task t = Task.Factory.StartNew(() => Console.WriteLine("Parallel"));
- t.ContinueWith(tsk => EventLog.WriteEntry("application", tsk.Exception.ToString()),
- TaskContinuationOptions.OnlyOnFaulted);
- }
- catch (Exception ex)
- {
- EventLog.WriteEntry("application", ex.ToString());
- }
- }
async / await pattern
using the async / await pattern we can handle both synchronic and parallel exception in the same place:
Code Snippet
- async void Foo()
- {
- try
- {
- Console.WriteLine("Synchronic");
- await Task.Factory.StartNew(() => Console.WriteLine("Parallel"));
- }
- catch (Exception ex)
- {
- // handling both synchronic and parallel exceptions
- EventLog.WriteEntry("application", ex.ToString());
- }
- }
when we are using the async / await pattern at compile time the compiler convert our code into continuation state machine.
therefore the compiler can take the code within the catch area and apply it both for the synchronic and the parallel execution.
Summary
async / await pattern does simplify the exception handling. we do write our exception handling once and it will apply for both synchronic and parallel execution.