So just to rephrase: Don’t make your Application lifetime events async void!Yes, I learned the hard way. Yes I’ve read, and know, about the: Never make a void async. But if you want write an event-handler you’ve got no choice. But beware, sometimes things look to be working okay, but actually don’t.Alright, back to where all my trouble started. Every Windows Phone App developer knows about the Application Lifetime events that are automatically subscribed to in the App.xaml.cs. You’ve probably added code to at least one of the following event-handlers.Application_Launching: Occurs when the application is being launchedApplication_Closing: Occurs when the application is exitingApplication_Activated: Occurs when the application is being made active after previously being put into a dormant state or tombstoned.Application_Deactivated: Occurs when the application is being deactivated. You have 10 seconds to complete your work, though it’s recommended to aim for completing the work within 2 seconds.No await in those event handlers!Alright, I’m just writing code. I need to perform the last small SQLite query to save some state. Hmm, that’s done in the Closing method. I’m writing the code, oh yeah, the SQLite query is an asynchronous operation. I write await, hmm, mark the method as async void. Hmm, shouldn’t do that, should I? It’s an event-handler, true, but don’t forget you’ve done it before, and the code does execute. Okay move on and test later. I’ll be honest, I forgot to test, but I got some strange issues that I had difficulty with solving.What I found out, that as soon as the word await was hit in the event-handler, the thread was given back to the application, which kind of signaled the app, I’m ready to terminate. Ouch! The actual never executed, that was painful! Just note, after save the settings in the SQLite database, I did the closing of all open connections. This closing never happened either, which in itself caused strange situations with trying to execute queries on closed connections when the app resumed.Okay I learned the hard way, don’t use await in the above mentioned event-handlers, better don’t use it in any event-handler.But I need that API call, which happens to be asyncSo I started looking for a way to call a Task synchronously. Yes I found a way on StackOverflow that works very well. So I could change my code like this, which indeed does result in nice code I think.

All the code that was originally in the Application_Closing event handler is now moved to the ApplicationClosingAsync method, which indeed is an async method which returns a Task. The method contains multiple await statements, the keyword that shouldn’t be in de event handler itself. I added the Debug information for testing purpose, so you can see everything get’s called. The magic is in the AsyncHelper method which I copied from the StackOverflow site, so please place the credits in the right place. I’ve shown the code for Application_Closing, but it works for the other event-handlers as well.UPDATE 1: According to Oren Novotny this feature also exists in the Nito.AsyncEx NuGet Package. Pick the one you like best, but at least test your code.

惰性的异步 － LazyAsync

I’ve been moving some data access code to to use Lazy<T> whenever I want to defer actually fetching the data until it’s first needed. What I’ve always found interesting is there is no Lazy Async.In the exact use case it’s when an application loads, there is some static data loaded from a database. This data is the cached for later use.However, in many situations it’s not actually needed until much later if at all. Why take the performance hit of fetching the data on app startup if that data is often times not needed?That’s the whole purpose of Lazy<T>. But as mentioned, why is there no Lazy Async? If i want to defer IO, that’s generally async.Here is more info on Lazy Initialization if it’s new to you.

SourceAll the source code for my demo is available on GitHub if you want to try it yourself.If anyone has any other suggestions or recommendations about blog topics, please leave comment or let me know on twitter.

Will you just wait a minute?! NUnit and Async/Await

I was being a good-doobie. Honest.I had written a prototype – just something to prove that a particular approach could work. It did, and so now it was time for me to actually bring that code up to production quality. Part of that meant modifying how I was invoking the third-party web services – they needed to be done asynchronously.So I went through and wrote my unit tests to also run asynchronously:

I ran it through NUnit on my machine, and everything was peachy-keen. I ended up writing nearly 50 unit tests* like that, converting over all of my calls. I committed the code, and let TeamCity take over.And watched every one of those new tests break.When I looked at the TeamCity log, the errors seemed to hint that the test runner was simply not waiting for the thing under test to complete before trying to run the asserts. I started searching for things like "nunit async", and pretty quickly across this two-part series by Stephen Cleary:

In this series, Cleary says that the underlying problem of running async tests is that they don’t have a proper context:

We’ve encountered a situation very similar to async in Console programs: there is no async context provided for unit tests, so they’re just using the thread pool context. This means that when we await our method under test, then our async test method returns to its caller (the unit test framework), and the remainder of the async test method – including the Assert – is scheduled to run on the thread pool. When the unit test framework sees the test method return (without an exception), then it marks the method as “Passed”. Eventually, the Assert will fail on the thread pool.

His solution is to simply give the test an async context, and he provides a very handy wrapper to do just that. I first had to install his Nito.AsyncEx NuGet package, and then wrap my test in AsyncContext.Run:

Notice that I’ve removed the "async" keyword from the test itself; AsyncContext.Run does all the work here. After updating and committing my first test using AsyncContext.Run – a test test, if you will – it ran successfully on TeamCity. I updated the other 48, and finally got a green build.***My build was stable again, but Cleary’s explanation didn’t answer the question of why this worked on my machine in the first place – without using his very awesome library – so, I kept digging.I first looked up exactly what TeamCity was using to run the tests – it was NUnit, the same as what was on my machine, with a minor different in the version. My local copy was 2.6.2, while the version on the build server was 2.6.1. Could there be a difference in how 2.6.1 was handling async?Why yes. Yes there was. In the NUnit 2.6.2 release notes I found this:

When running under .NET 4.5, async test methods are now supported. For test cases returning a value, the method must return Task<T>, where T is the type of the returned value. For single tests and test cases not returning a value, the method may return either void or Task.– Source: http://nunit.org/index.php?p=releaseNotes&r=2.6.2

Are you serious? I just happen to have the first version of NUnit that would properly handle async on my machine, but the build server was one notch older, and therefore couldn’t? *facepalm*To further prove that this was the real source of my issue, I installed NUnit 2.6.1 and 2.6.2 side by side on my machine. I took my two tests from above, both of which should have tried to execute the MathLibrary.Divide function which included a 2-second delay: public class Math { public async Task<float> Divide(int Numerator, int Denominator) { await Task.Delay(2000); return Numerator / Denominator; } }When I ran these two tests through NUnit 2.6.1, Divide_4DividedBy2_Equals2 completes in a couple hundredths of a second, while Divide_4DividedBy2_Equals2_Asynchrofied takes just over 2 seconds to complete, for a total of just over 2 seconds:When I ran these through NUnit 2.6.2, EACH test takes just over 2 seconds to complete, for a total of just over 4 seconds:So, I have two choices – switch my builds on TeamCity to use at least NUnit 2.6.2 to run the tests, or use Cleary’s Nito.AsyncEx library, which will allow me to leave the build server as is. In any event, at least I have a reasonable explanation for what was happening. The funny thing is that it’s usually MSBuild that messes with me. Apparently NUnit gave him the week off.

* Yes, I realize that by calling the service directly, this no longer counts as a "unit" test, but rather an integration test. That distinction isn’t relevant to the issue described in this post, though, so I’m going to gloss over the mock objects in the real code.