Archive for the ‘Multi Thread’ Category

Async calls and the .NET 4.5

Posted: April 1, 2013 in .NET, Multi Thread

Multi Processing and multi thread is always a challenge for any developer. The .Net Framework offers a very rich multithreading and parallel programming model, in the new framework we have an easy way to use multi processing, in this post we will take a look on the way we can use the new .net keywords and we will remember some of the basics about multi threading in the .Net platform.

In the analysis of this topic we will use C# as our language,

Remember the basics


We can define a Thread as a execution path within an application. Under the .NET framework there is not a correspondence between an application and domain Threads, a appDomain can have different execution paths running at the same time. A Thread is not confined to a single appDomain, they are free to cross application boundaries, but a thread can execute in only a appdomain in each moment.

“the CLR is the entity that is in charge of moving threads into (and out of) application domains and contexts. As a .NET developer, you can usually remain blissfully unaware where a given thread ends up (or exactly when it is placed into its new boundary). Nevertheless, you should be aware of the various ways of obtaining the underlying primitives.” (Andrew Troelsen).

Like we had said before .NET framework offer’s a rich api for parallel and multi Threading program, you can use Delegates as a way to have different execution paths in concurrency or the Thread object you also have parallel programming, but one off the things a lot of developer’s say is that the objects .NET offer’s are not easy to use, for that reason in .NET 4.5 the API offer us a new way to deal with async calls.

async and await

The async keyword qualify a call as asynchronous (this is valid for methods, lambda expressions, anonymous methods), the use of this keyword pass the message that the call will be automatically async. In the backstage what happens when you call a  method that was tagged with the async keyword, the CLR will create a new thread of execution to handle the task at hand.


Class Test{

public async void asyncMethod(){  …… }


It should be very clear in your mind that when you call a method that was declared as a async method is that your call will be called in a asynchronous manner. If you wish to stay blocked in the call of a method that was declared as async you should use other helper C# keyword named await.

Based in what we had seen a call to our method without need to block would be something like this (consider obj as an instance of Test)


If we intend to wait for the method processing we should do something like:

await obj.asyncMethod();

Right now maybe you are thinking that this keywords helps you to do more clean code, but how to use this anti pattern to execute asynchronous result dependent tasks (this is fair away the most interesting thing of the use f this keywords). Let´s reconsider our Test class and a asyncMethod2 that returns a task

Class Test{

public async Task asyncMethod2(){  …… }


A Task is an object that represents a paralell action (

“The Task parallelism refers to one or more independent tasks running concurrently. A task represents an asynchronous operation, and in some ways it resembles the creation of a new thread or ThreadPool work item, but at a higher level of abstraction. Tasks provide two primary benefits:

  • More efficient and more scalable use of system resources.Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.
  • More programmatic control than is possible with a thread or work item.Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

One example of a call to wait 2000 ms after the return of the asynchronous method

await obj.asyncMethod2.Run(() => { Thread.Sleep(2000); });

Other most sophisticated example:

public class Worker
    public async void DoWorkAsync(Action action)
        Console.WriteLine("  Before DoWorkAsync");
        await Task.Factory.StartNew(action.Invoke);
        Console.WriteLine("  After DoWorkAsync");

//Step 1
        var sl = new SpinWait();
        int max = 100000;
        Worker w = new Worker();

        //Step 2
        Console.WriteLine("Start worker");
        w.DoWorkAsync(() =>
                Console.WriteLine("  Before actual work");
                for (int i = 0; i < max; i++)
                Console.WriteLine("  After actual work");

        //Step 3
        Console.WriteLine("Returned to main");


as a result we will see in the console the output

Start worker
  Before DoWorkAsync
Returned to main
  Before actual work
  After actual work
  After DoWorkAsync

I hope this post had help you to understand where async and await feet in, and what the opportunities this keywords bring. One off the great values of this 2 keywords is the simplicity to do asynchronous calls.

If you have any question feel free to ask.

Foot Note

to know event better the async keyword we recommend you to go to the MSDN article