How to debug a wait expression?

I recently saw several presentations on TPL and asynchronous pattern, so I started a small project for pets to try some things. (Both asynchronous and parallel material)

I noticed that SqlConnection has an OpenAsync () method, so I wanted to try it on hold. As far as I understand, the await keyword tells the compiler to check if the operation is complete and if it does not convert the rest of the code into a continuation task. I also realized that I still have to debug the code. However, I have 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 get into the wait statement, but no further. I tried to set breakpoints in both the catch statement and the code specified in the try block. Both are not reached, and the console application just shuts down. I don’t understand what is going on here.

I am using VS2012 update 1, (VB) .Net 4.5. In addition, since I suspected that some error had occurred (which really does not make sense, since the code works when I make it synchronous), I configured app.config to escalate invisible exceptions:

 <runtime> <ThrowUnobservedTaskExceptions enabled="true"/> </runtime> 

However, so far I have not received any exception. What am I missing? Please, help:)

+4
source share
1 answer

Both are not reached, and the console application just shuts down.

The problem is that you are using this in a console application. If you do the same in a Windows Forms or WPF application, you will see completely different behavior.

When you call Await , an asynchronous operation tries to capture the caller's synchronization context, and then continue in that context. There is no synchronization context in the console application (since there is no message pump, etc.), therefore, the created continuation receives the scheduled ThreadPool thread.

The asynchronous operation starts, then everything continues - and the console application ends, as it reaches the end of the main () procedure, and you never "see" the material later.

If you want this to happen, you need to add something to the console application so that it does not end. For example, you can use ManualResetEvent and set it after SomeCode() and call WaitOne() in your main () procedure. This will save the application until the asynchronous operation completes.

If you are trying to understand Async / Await , I would recommend playing in a graphical application, rather than in a console application. It is much easier to see and understand what happens when you have the proper synchronization context set in, which happens automatically in Windows Forms and WPF.

+6
source

All Articles