Being Cellfish

Stuff I wished I've found in some blog (and sometimes did)

TPL Dataflow and async/await vs CCR - part 1

Change of Address
This blog has moved to blog.cellfish.se.

TPL Dataflow and async/await vs CCR - part 1

  • Comments 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.

  • Please note that I made an update to this post. I noticed that I (again) made a mistake and only tested the first thing (async test method) with a very simple async method that actually completed synchronously. Turns out that does not currently work... Sad face.

Page 1 of 1 (1 items)