TPL Dataflow and async/await vs CCR - part 1

As when working with CCR, working with async/await you need to have good tools for writing tests and execute the asynchronous code synchronously. I wish it was this easy:

  1: [TestMethod]
 2: public async void WithAsync()
 3: {
 4:     Assert.AreEqual(42, await DoSomething());
 5: }

Unfortunately this does not work and I hope it changes before the next version of Visual Studio ships. But even if it did work it is not perfect. Since it's test code you probably want to have some timeout when you wait. Most test frameworks allow you to have a timeout on your test and the default is typically very long. If your framework does not support that or you want more granular control you can use a nifty little extension method like this:

  6: public static class AsyncExtensions
 7: {
 8:     public static T WaitForResult<T>(this Task<T> task, TimeSpan timeout)
 9:     {
 10:         if (!task.Wait(timeout))
 11:         {
 12:             throw new TimeoutException("Timeout getting result");
 13:         }
 14:  
 15:         return task.Result;
 16:     }
 17: }

Using that extension method the test above would look like this:

  18: [TestMethod]
 19: public void WithTimeout()
 20: {
 21:     Assert.AreEqual(42, DoSomething().WaitForResult(TimeSpan.FromSeconds(5));
 22: }

As you can see this beats the use of synchronous arbiters and causalities for tests which were needed to test CCR.