How to debug a await statement?

async-await, vb.net

Solution

Both are not reached, and the console application simply quits.

The problem is that you're using this in a Console Application. If you were to do the same thing in a Windows Forms or WPF app, you'd see very different behavior.

When you call `Await`, the asynchronous operation tries to capture the synchronization context of the caller, and then continue on that context. In a console application, there is no synchronization context (since there's no message pump, etc), so the continuation created gets scheduled on a ThreadPool thread.

The asynchronous operation is started, then things continue on - and the Console Application ends, since it reaches the end of the Main() routine, and you never "see" the stuff afterwards.

If you want to see the stuff happen, you'll need to add something to your console application to prevent it from completing. For example, you could use a `ManualResetEvent` and set it after `SomeCode()`, and call `WaitOne()` in your Main() routine. This would keep the application alive until after your asynchronous operation completed.

That being said, if you're trying to understand `Async`/`Await`, I'd recommend "playing" in a GUI application instead of a Console application. It's far simpler to see and understand what's happening when you have a proper Synchronization Context installed, which happens automatically in Windows Forms and WPF.

Problem

I recently saw some presentations on the TPL and on async pattern, so I started a little pet project to try out some things. (Both async and parallel stuff) I noticed that SqlConnection has an OpenAsync() method, so I wanted to try out awaiting this. As I understand it, the await keyword tells the compliler to check if the operation is finished, and if it isnt it will convert the rest of the code to a continuation task. I also understood that I should still be able to debug the code. However, I am having some problems with this. I wrote the following simple test code: ``` Async Sub Gogo() Try Await connection1.OpenAsync() Catch ex As Exception Console.WriteLine(ex) End Try SomeCode() End Sub ``` What happens when I run this code (console application) I do get to the await statement, but not any further. I tried setting breakpoints both in the catch statement and in the code following on the try block. Both are not reached, and the console application simply quits. I dont understand what happens here. I am using VS2012 update 1, (VB).Net 4.5. Also, because I suspected some error occurs (which does not really seem to make sense, because the code works when I make it synchronous) I configured the app.config to escalate unobserved exceptions: ``` <runtime> <ThrowUnobservedTaskExceptions enabled="true"/> </runtime> ``` However, I didnt get any exception so far. What am I missing? Please help :)

Original source