How To: MVC 4 + Async CTP = Asynchronous Controller Implementation

by CezaryN 7. March 2012 12:18

Quick introduction

This article presents the following:

MVC4 Beta with Visual Studio Asynchronous Programming (Async CTP) used to implement MVC asynchronous controllers.

The example uses await keyword with a task that was produced for a pair of asynchronous BeginOperation and EndOperation methods.

Used components and necessary downloads:

Why this article is different?

Most of the examples show the use of await keyword with a method that is declared with async keyword. This one shows a sample with pair of asynchronous BeginOperation and EndOperation methods.

Step by step instructions and code

Can you remember the times when a page in classic ASPX or MVC was written in one method, not in a form of the pair of asynchronous methods? The ease of beauty of just one method is back with the use of Visual Studio Asynchronous Programming. Asynchronous pages and controllers are back with all the goodness and scalability of asynchronous programming, but with ease of implementation in just one method.



Programming | .Net 4.0 | TPL (Task Parallel Library) | ASP.Net | MVC4

How To: Linq Left Outer Join

by CezaryN 5. March 2012 23:23

Some time ago I was struggling with Linq and left outer join. By default Linq extensions provide Join method (an inner join) but not the left outer join method.

I worked out the following method implementation. That is the fastest I came up with.

public static class EnumberableExtensions
    /// <summary>
    /// Produces a left outer join of two IEnumerable collections.
    /// </summary>
    /// <typeparam name="TOuter">The base sequence.</typeparam>
    /// <typeparam name="TInner">The sequence to join the first 
/// sequence.</typeparam>
/// <typeparam name="TKey">The type of the key used in both
/// types.</typeparam>
/// <typeparam name="TResult">Type stored in the resulting
/// IEnumerable collection.</typeparam>
/// <param name="outer">The outer collection.</param> /// <param name="inner">The inner collection.</param> /// <param name="outerKeySelector">A function to extract the join
/// key from each element of the first sequence.</param>
/// <param name="innerKeySelector">A function to extract the join
/// key from each element of the second sequence.</param>
/// <param name="joinMethod">The method that takes an element from
/// the first sequence and an element from the second sequence and
/// builds the result element based on the input elements for the
/// joined sequence.</param>
/// <returns></returns> public static IEnumerable<TResult> JoinLeftOuter<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> joinMethod) where TInner : class { var result = outer .GroupJoin( inner, outerKeySelector, innerKeySelector, (o, i) => new
key = outerKeySelector(o),
outer = o,
innerGrouped = i.Select(e => e)
}) .SelectMany( e => e.innerGrouped.DefaultIfEmpty().Select(r => joinMethod(e.outer, r))); return result; } }
This uses the GroupJoin method and then flattens out the results using SelectMany method. The method allows you to specify the method that takes an element from each sequence and allows to produce the resulting sequence element. This allows an easy transformation of the data into desired class. A sample usage:
List<DataClass> ll = new List<DataClass>();
ll.Add(new DataClass() { id = 1, data = "aaa" });
ll.Add(new DataClass() { id = 2, data = "aaa" });
ll.Add(new DataClass() { id = 3, data = "aaa" });
ll.Add(new DataClass() { id = 4, data = "aaa" });

List<DataClass> lr = new List<DataClass>();
lr.Add(new DataClass() { id = 2, data = "rr_aaa" });
lr.Add(new DataClass() { id = 3, data = "rr_bbb" });
lr.Add(new DataClass() { id = 3, data = "rr_ccc" });
lr.Add(new DataClass() { id = 5, data = "rr_ccc" });

var res = ll.JoinLeftOuter(
    l =>,
    l =>,
    (o, i) => new { id =, data =, inner = i });

foreach (var e in res)
    Console.WriteLine( + ", " + + 
            e.inner == null ? 
            "" : 
            ", " + + ", " +;
The output presents the following results:

1, aaa
2, aaa, 2, rr_aaa
3, aaa, 3, rr_bbb
3, aaa, 3, rr_ccc
4, aaa

Please note, how nicely the outer join worked:
  • the ids 1 and 4 of the first sequence don’t have the matching elements in the second sequence and still appeared in the result
  • the id 3 of the first sequence is matched with both ids 3 from the second sequence
  • the id 5 from the second sequence does not appear as it hasn’t got a matching element in the first sequence
The method is pretty fast. For 10 000 elements in the first sequence and 30 000 elements in the second sequence, the enumeration (producing the result using ToList()) takes around 60 miliseconds on a moderate laptop. Please note, how the joinMethod is declared and its role.

Have fun and feel free to re-use.

Tags: ,

Programming | .Net | .Net 4.0

IIS “Service Unavailable” HTTP 503 Error due to "Enable 32-Bit Applications" setting

by CezaryN 4. January 2012 16:08


I just finished diagnosing an IIS “Service Unavailable” HTTP 503 error.

That was a bit tricky. Every request to the web site on IIS was causing the error page with the following info to appear:

Service Unavailable
HTTP Error 503. The service is unavailable.


and was causing the application pool the website was configured for to crash.

There was no specific information in the event logs, IIS logs, nowhere. Simply, the application pool was crashing and IIS outputing the page with the error.



Tags: , ,

Programming | .Net | ASP.Net

WinDbg: .load sos clr and .load sos mscorwks errors

by CezaryN 14. December 2011 11:00

Recently I was trying to debug a memory dump of a .Net Clr 2.0 process on a machine with Visual Studio 2010 installed.

WinDbg failed to load the sos extension with the commands:

.load sos clr

.load sos mscorwks


I was getting the following error messages:

The call to LoadLibrary(sos clr) failed, Win32 error 0n2
    "The system cannot find the file specified."
Please check your debugger configuration and/or network access.

The call to LoadLibrary(sos mscorwks) failed, Win32 error 0n2
   "The system cannot find the file specified."
Please check your debugger configuration and/or network access.


Specifying the exact path for the version of the binary file to load did the trick: 

.load c:\Windows\Microsoft.NET\Framework64\v2.0.50727\SOS.dll
.load c:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll


From now on, I was able to debug the dump with the SOS extensions corresponding to the .Net version the executable binaries were built for.

Tags: , , ,

Programming | .Net | Visual Studio

Visual Studio - nice shortcut

by CezaryN 10. December 2011 14:47

Recently I started to use a new Visual Studio shortcut. Well, new to me, many people probably know it:

CTRL + , (control + comma)

Start typing and search for files, classes, methods, etc. Works nicely, fast and is very useful.

You can actually use it, when you are on a class, method or property name and it will automatically paste it into the search box. In this way you can search for different implementations of the same method (for an interface) or overridden virtual method, etc.

One of the most useful shortcuts.

Tags: , ,

Programming | .Net | Visual Studio

Task Parallel Library step by step, Adventure 3 – Parallel LINQ (PLINQ)

by CezaryN 30. January 2011 17:35


This article is a continuation of the Task Parallel Library articles that started with and This article describes Parallel LINQ and is describes task parallelization when working on IEnumerable data sources. The article describes what elements of PLINQ query execution elements can be parallel and how we can influence query parallelization.

All the samples in their final version are available with the source code to experiment with: MTS2010-01-samples.ZIP (40 kb) 


The samples here base on the starting sample described in the Parallel.ForEach sample of  the previous articles. This time we are concentrating on using DoSOmething in the PLINQ query clauses.

PLINQ is fun!

Sample: 03_PLINQ_01_simple

Step: Starting with LINQ query

Let’s start with a simple LINQ query to see how the sample works. We have a simple array (IEnumerable data source), we create a query that executes a Where clause and a Select clause, both use the DoSomething (they could use some different code!), and the Where lambda expression always returns true (so all elements get selected). The sample code is simple and straightforward:

Console.WriteLine("Main thread: {0:d3}, {1}",

int[] arr = Enumerable.Range(0, 5).ToArray<int>();

var queryLinq = arr
    .Where((e) => { DoSomething(e); return true; })
    .Select((e) => { return DoSomething(e + 100); })

foreach (var e in queryLinq) 
    Console.WriteLine("ForEach: " + e.ToString()); 

Tags: ,

Programming | .Net 4.0 | TPL (Task Parallel Library)

Task Parallel Library step by step, Adventure 2

by CezaryN 9. January 2011 16:36


This article is a continuation of the Task Parallel Library articles that started with This article describes Task Parallelism and is oriented towards tasks (not data), tasks launching, task continuation, returning values from tasks, nested and child tasks.

All the samples in their final version are available with the source code to experiment with: MTS2010-01-samples.ZIP (33.27 kb) 


The samples here base on the starting sample described in the Parallel.ForEach sample of  the previous article.

Let’s quit looping and switch to tasks

Sample: 02_TP_01_task_simple

Step: Creating and starting tasks

The first step is to replace the Parallel.ForEach with TPL tasks. We declare an array of Task  objects, create the Task objects and start them:

Task[] tasks = new Task[arr.Count<int>()];

for (int i = 0; i < arr.Count<int>(); i++)
    tasks[i] = new Task((obj) => 
        DoSomething ((int)obj), 

for (int i = 0; i < arr.Count<int>(); i++)

Now, let’s see the difference in the code execution, as compared to Parallel.ForEach. The execution sequence is presented on the screenshot below:


We can clearly observe that the task execution is non-blocking (all the tasks were started after the Main() method of the console application printed out “Finished”) and that the default execution of the tasks takes place on the ThreadPool threads.

We can instruct TPL with TaskCreationOptions about some of our preferences, for instance, we can use TaskCreationOptions.LongRunning (to instruct TPL to use a regular, non-ThreadPool thread) or TaskCreationOptions.PreferFairness (to instruct TPL to try to execute the tasks in the order they were started – note, there is no guarantee it would be done this way).

Sample usage of the options could look like:

Task[] tasks = new Task[arr.Count<int>()];

Console.WriteLine("Main thread: {0:d3}, {1}",

for (int i = 0; i < arr.Count<int>(); i++)
    tasks[i] = new Task((obj) =>
        TaskCreationOptions.LongRunning | 
TaskCreationOptions.PreferFairness); } for (int i = 0; i < arr.Count<int>(); i++) tasks[i].Start();


As compared to Parallel.ForEach, we can make the following observations:

  • Tasks, as opposed to Parallel.ForEach, would be non-blocking
  • We can force execution on a non-ThreadPool thread
  • We can request TPL to try execute

Tags: ,

Programming | .Net 4.0 | TPL (Task Parallel Library)

Task Parallel Library step by step, Adventure 1

by CezaryN 1. November 2010 13:43


Following the promises, I am starting with the first article related to Task Parallel Programming. I think a remarkable progress has been done here and it is worth taking a few minutes to go through the features and capabilities of TPL (Task Parallel Library).

The purpose of the articles (I am splitting the material into few articles) is to present the capabilities of TPL in the form of simplest, shortest code samples accompanied by explanations and observations. So, I created a series of very simple examples with similar structure and will go from one example to another, with very small modifications to show the features of TPL and how those simple modifications impact the code execution.

The samples present the following features of TPL:

  • task activation depending on the CPU load
  • data parallelism (Parallel.ForEach, task partitioner)
  • ParallelOptions
  • task cancellation (CancellationToken, CancellationTokenSource, Cancel, Break)
  • task parallelism (starting tasks, continuation tasks, returning values, nested and child tasks)
  • PLINQ (Parallel Linq) (AsParallel, AsOrdered, AsSequential, WithMergeOptions, WithExecutionMode, WithDegreeOfParallelism, …)
  • custom task schedulers and task factories
  • TPL exception handling

For the purpose of this article, I am running the samples on a dual core laptop, so we can observe some parallel execution. Nonetheless, depending on the number of cores and the CPU speed, you might want to tune the number of tasks, looping iterations or CPU heavy instructions. Feel free to modify the parameters and observe the results. It’s fun to see ho the behavior changes when you play with the values.

All the samples in their final version are available with the source code to experiment with: MTS2010-01-samples.ZIP (33.27 kb)  


At first, let’s take a look at the code samples structure.

  • The samples are console applications, Visual Studio 2010 (.Net 4.0) version (obviously…) and follow the the same structure,
  • We have a DoSomething() method that will simulate our parallel tasks or jobs (the parameters of DoSomething() will vary slightly from sample to sample),
  • In the console application’s Main() method we are starting the tasks and outputting some information,
  • The DoSomething() method outputs to the console some information at its starting time:

    Console.WriteLine("{0:d4} ST: {1:d3}, {2}", pvalue,
    and its finishing time:
    Console.WriteLine("{0:d4} ET: {1:d3}, {2}", pvalue, 
    where pvalue is our task or job identifier, “ST” and “ET” symbolize “StartTask” and “EndTask” appropriately, we output as well the managed thread id that the task is running on and whether the thread is a ThreadPool  thread. Sometimes, we output some additional information, but this is the most crucial information we need to observe the thread behaviors,
  • The DoSomething() method has some looping to simulate the work, sometimes does nothing, sometimes we put some heavy CPU work on the loop to simulate CPU intensive operations,
  • Additionally, at the beginning of Main() we output similar properties for the Main’s thread and output “Finished” when Main() finishes.

How to move a folder in Windows Live Mesh 2011

by CezaryN 25. October 2010 21:28

I spent quite a considerable time trying to move a synced folder in Windows Live Mesh 2011. This is a bit twisted and very unintuitive.

Described in help for Windows Live Mesh 2011:

I tried to work with One Note 2010 and synced folders and it works beautifully! :)


Welcome! Or how deep the rabbit whole goes...

by CezaryN 24. October 2010 20:27


So, eventually, that day came. I jumped into the rabbit hole of blogging. Planned for a long time, topics gathered. What happened? I presented two sessions on MTS 2010 (Microsoft Technology Summit) in Poland. Both sessions were presenting .Net 4.0 Task Parallel Library topics. The sessions were very well received, so I decided that those would be great topics to start with.

So, expect very soon a series of posts dedicated to Task Parallel Library, with samples, code, explanations, etc.

And welcome to my blogging page! :)

Cezary Nolewajka


Powered by BlogEngine.NET
Theme by Mads Kristensen | Modified by Mooglegiant