Skip to main content

A Task chaining refactoring with an example

This was a very long break since I posted my last web note however it`s time to share some fresh experience with the developer community. Today I want to show one of a handy solution which allowed me to simplify a Task chaining in .NET 4.5.1.

Let`s start from defining a problem which in this case is a Task.ContinueWith<TResult>  method and the way how it`s designed for a tasks chaining. So if you want to use a chaining by using this function, all the time you need to access a parent task result property which in many cases causes a lot of redundancy in the code. To demonstrate this I use a simple async WebApi2 GET cities  auto-complete function which will query a database and later map result set of entities to collection of data transfer objects (DTO).

// !!BADLY DESIGNED CODE!!
[HttpGet]
public async Task<HttpResponseMessage> Get(string query)
    {
         return await this.cityRepository
         .AutocompleteCityAsync(query)
         .ContinueWith<HttpResponseMessage>(parentTask =>
            {
                var cities = parentTask.Result.MapCollection<TCity>();

                //Returns HttpResponseMessage.
                return this.CreateListResponse<TCity>(cities);             });     }

As you can see in the example above by awaiting a citiRepository.AutocompleteCityAsync function I started an asynchronous operation (Task). When this function returns a result a next piece of code going to be invoked as I used a ContinueWith<T> function where T is a type of results that my continuation code returns. The problem is that in chained code I need to deal with a previous task itself and the only way to retrieve result of it is to access a Result property directly.

public static Task<TNewResult> Continue<TResult, TNewResult>(
 this Task<TResult> task,
 Func<TResult, Task<TNewResult>> continuation)
    {
        if (task == null)
        {
            throw new ArgumentNullException("task");
        }
 
        if (continuation == null)
        {
            throw new ArgumentNullException("continuation");
        }
 
        return task
            .ContinueWith(innerTask => continuation(innerTask.Result))
            .Unwrap();
    }


The continuation code can be easily re-factored by creating a simple extension method for a Task<T> type. As presented in code above, just by centralizing a call of the ContinueWith function with a custom continuation function followed by a Unwrap method a chaining become much cleaner. So then a Continue<TResult, TNewResult> function knows a type of result from a parent task and also know what type a continuation code going to return. Therefor let`s use it an see how a chaining looks like after I use my extension method. Please note that I`m not accessing a  parent Task.Result directly and instead of this I working just with a type returned by this task.

 [HttpGet]
 public async Task<HttpResponseMessage> Get(string query)
       {
           return await this.cityRepository
               .AutocompleteCity(query)
               .Continue<IQueryable<City>, HttpResponseMessage>(entities =>
               {
                   var cities = entities.MapCollection<TCity>();
                   return this.CreateListResponse<TCity>(cities);
               });
       }

So as conclusion, just by using a simple extension method, I was able to successfully re-factor a common task chaining logic which results in having more cleaner and easier to understand code.

Popular posts from this blog

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileSt...

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition...

Using Newtonsoft serializer in CosmosDB client

Problem In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB.  Solution In CosmosDBV3 .NET Core API, when creating an instance of  CosmosClient one of optional setting in  CosmosClientOptions is to specify an instance of a Serializer . This serializer must be JSON based and be of  CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from  CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex.  For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from  CosmosSerializer.  using  Microsoft.Azure.Cosmos; using  Newtonsoft.Json; usin...