Using async/await with IAsyncResult pattern

Even though in my current project we use .NET 4.5 we still have lots of references to internal libraries targeting .NET 4.0. Usually it is not a problem, however some of these libraries follow Asynchronous Programming Model pattern. This approach makes the code quite ugly because we end up with lots of nested callbacks.

Fortunately thanks to

method it is possible to quite easily make Begin/End methods work with async/await pattern. All you have to do is to pass Begin/End methods as an arguments to Task.Factory.FromAsync and you are good to go. The original code after refactoring looks like that

I think everyone will agree with me that refactored version is much better than original one.
Source code for this post can be found here

Using async/await with IAsyncResult pattern

EntityFramework – SQLException during database migration

Recently I’ve been doing some small refactoring of my pet project. Nothing too fancy – just namespace adjustment, variables and class renaming etc. However it turned out that even these minor changes can in fact be major ones. All of the sudden most of my integration tests started failing due to SQLException.
Exception
I am using Code First approach so I didn’t take me too much time to realize that for some reasons EntityFramework wanted to create already existing tables. I started looking into the way EF keeps track of the changes in the model and it turned out that it creates special table called

ContextKey
One of the most important columns in there is column called ContextKey, which identifies the class which describes migration policy. In my case this class originally looked that way

In that case value of the ContextKey column matches the full name of the class

The class after refactoring was slightly changed and now it looks that way

It is easy to overlook the change but now, full name of the class is

so EF loses the information about the migration and tries to migrate once again from the scratch. Fortunately there is an easy fix for that which doesn’t require dropping the database. All you have to do is to write simple update statement which set the proper ContextKey value.

Source code for this post can be found here

EntityFramework – SQLException during database migration

Abusing collection initializers

Most of .NET developers are familiar with collection initializers syntax. Long story short, this language feature allows you to replace this ugly syntax

with much shorter and cleaner one

The more interesting thing is the fact that you can leverage this syntax not only for build-in collections but also for your custom classes. In order to do that your class must implement IEnumerable interface and expose public Add method. Let’s assume that we have some real case scenario and we have class which looks like that

This is a simple wrapper over the List. At this moment we can’t use collection initializer when constructing objects of this classs. However by adding method Add

we can create a new instance of that class just like we would do with List

What is more, it is possible to have multiple overloads of Add method in our class, so for instance if we add

we are able to use this syntax

In addition it is even possible to use a mix of Add overloads

Add method can also have multiple arguments

in that case we are able to use this syntax

The last thing I would like to point out is that Add function doesn’t have to be an instance method, we can easily implement it as an extension method and still leverage the collection initializer syntax.

Now with proper namespace import we can write this code

Source code for this post can be found here

Abusing collection initializers

TPL – exception handling and UnobservedTaskException issue

1. Introduction

Working with Tasks is a modern way of writing asynchronous code in an easy and flexible manner. It is quite straightforward to start using them, so usually developers do not investigate thoroughly the topic. Unfortunately this often leads to unpleasant surprises – especially when it comes to exception handling. Having this in mind let’s take a look how to handle exceptions in Task and what can happen if we do it wrong.

2. Exception handling

Because of the fact that Tasks are run asynchronously we can’t just use a standard try catch block surrounding Task

In that case catch block is unreachable (I will describe later what happens with that exception), of course we could use try catch inside Task.Factory.StartNew lambda expression but this is not always the case. Usually we want to handle exception in the caller of the Task, not inside the Task itself. There are couple of ways of achieving that – depending on the situation you can use one of the following ways. Exception are propagated to caller once you start waiting for the result of Task. So basically you can use try catch block if you wait for a Task to finish – either by accessing Result property or using Wait method

However accessing Result or calling Wait method are blocking calls, so this might not be a perfect solution for every scenario. Fortunately we can also leverage ContinueWith method which gives you an ability to specify what should be done once Task finishes processing the operation. What is more important you can configure this method to only be called if exception occurs. Nonetheless there is one crucial thing you have to remember – in order to make exception handled or observed you have to access Exception property of Task

or call Handle method from AggregateException object

Otherwise exception will not be handled which may cause a lot of troubles described in section 3 of this post. Lastly if you use .NET 4.5 you can also just use async await and try catch block

3. Handling UnobservedTaskException

If it happens that exception thrown by Task is not handled, once the Task is garbage-collected, finalizer thread will throw UnobservedTaskException.

The implication of this depends on framework we are running our application on. If you run your app on .NET 4.5 or later version, with default escalation policy, TaskScheduler.UnobservedTaskException event will be raised and basically that is all. No more further problems, so basically you may not even realize that there is something like UnobservedTaskException. However if we add this entry

to app.configour process will be killed once UnobservedTaskExceptionis is thrown.
UnobservedTaskExceptionis
The problem arises in .NET 4.0 (if you run your app on .NET 4.0 not only compile it against this framework version), in this version of framework default escalation policy is very strict and will kill our process once the UnobservedTaskException is thrown by finalizer thread. Furthermore you cannot change this policy using app.config. Fortunately there is a one last chance to handle UnobservedExceptions and prevent our process from being killed. All you have to do is to wire up TaskScheduler.UnobservedTaskException static event handler and then set exception to observed state

There is one more thing to clarify. You can compile your library against .NET 4.0 but if you have .NET 4.5 installed on your machine, your application is launched and run on .NET 4.5. This means that escalation policy from .NET 4.5 will be used – so by default process will not be killed. In order to simulate pure .NET 4.0 behavior while having .NET 4.5 installed you have to add

in your app.config as it was mentioned before. Otherwise you would have to uninstall .NET 4.5 in order to, for example reproduce production issue. Source code for this post can be found here

TPL – exception handling and UnobservedTaskException issue

Easy way to suppress code analysis warnings

Everyone who has ever been using a code analysis knows that sometimes it is hard to follow the Microsoft coding guidelines and it is necessary to suppress some warnings. For me it always was a painful operation because I didn’t know any automated way of doing that. So basically I had to find the warning in the MSDN, copy category, code and other necessary stuff and then manually add appropriate attribute in code. Fortunately a friend of mine yesterday showed me a simple trick to generate this attribute with couple of mouse clicks. All you have to do is to right-click on warning message and choose Suppress Message context menu …
code analysis

There are two options in there. The first option – In Source, will add attribute directly in the code

code analysis
and the second one – In Suppression File, will create GlobalSuppressoins.cs file with assembly attribute which suppresses given warning in entire assembly

code analysis

Easy way to suppress code analysis warnings