Anything related to the .NET framework
08 May 2012

.NET 4.5 Baby Steps, Part 2: Task timeout cancellation

Other posts in this series can be found on the Series Index Page


When Tasks where introduced in .NET 4 one of the fantastic abilities was to be able to pass in a CancellationToken and use that to cancel/break out of tasks (think like a cancel button on a file copy).

So in the following code we create a cancellation source and pass the token to the task and it will output the date/time until you press enter. Then we call the Cancel method and it stops.

var cancelTokenSource = new System.Threading.CancellationTokenSource();

Task.Factory.StartNew(() =>
    while (!cancelTokenSource.IsCancellationRequested)
}, cancelTokenSource.Token);

Console.WriteLine("Press any key to cancel");


What is new in .NET 4.5?

.NET 4.5 adds a FANTASTIC new feature to this, the ability to cancel automatically after a set timeout! So all we need to is change the constructor and set the time out. In the demo below it is set to three seconds.

It is also important to note that it is time from when you create the token source and not time from when the task starts.

var cancelTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3))

Below in the screen capture, see how the word Done does not appear but processing stops? That is because it is cancelled (processing stopped) but I never pressed any keys – so it is still waiting for the readline above Done.


Package icon Cancellation Token Demo Code7.75 KB
08 May 2012

.NET 4.5 Baby Steps, Part 1: ThreadLocal<T>

Other posts in this series can be found on the Series Index Page


ThreadLocal<T> was introduced in .NET 4 and didn’t get much attention because it didn’t do much over the ThreadStaticAttribute which we have had since version 1 of the framework, so let’s just review what it does. In short it gives every unique thread that uses it, it’s own global field. Let’s look at this code:

static ThreadLocal<int> balances = new ThreadLocal<int>(() =>
        return 10;

static void Main(string[] args)
    for (int i = 0; i < 10; i++)
        new Thread(AddMoney).Start();


static void AddMoney()
    Console.WriteLine("Before {0}", balances.Value);
    balances.Value += new Random().Next(0, 1000);
    Console.WriteLine("After {0}", balances.Value);

Which produces:


Note that ever Before is set to 10 and that is because the lambda method that we pass to the ThreadLocal<T> constructor is run for each unique thread.

What’s new in .NET 4.5?

.NET 4.5 improves the usefulness of this by including the .Values parameter which allows you to list the results from each thread! To make use of this you need to opt-in in the constructor by adding true:

static ThreadLocal<int> balances = new ThreadLocal<int>(() =>
    return 10;
}, true);
And then in my demo I will output the results using:
foreach (var item in balances.Values)
    Console.WriteLine("Balance at end: {0}", item);


This is VERY useful when working with threads and doing individual calculations and then collating the results at the end!


ThreadLocal<T> only works with unique threads! So using with the TPL or ThreadPool which reuse threads will not work as expected!

Package icon Complete Demo Code7.62 KB
17 Apr 2012

South African Postal Codes for Windows Phone

1I can NEVER EVER remember the postal code for where I work or where I live – that little four digit number just eludes my brain. So to solve that I thought, why can’t I have EVERY postal code with me always? So that is what I made happen with this simple Windows Phone application: Postal codes!

It is dog simple: one input the name of what you want then hit search and boom results. It includes both street and box codes Smile

For the developers out there, this application source code is available too at:

11 Apr 2012

Windows 8 for the .NET developer

Last night I presented on Windows 8 for the .NET developer at the fantastic Developer User Group! We had a bumper crowd there which was great and really had some interesting discussions during and after the talk. Thank you to all that attended!

For those looking for the slides, demo script and demo bits they are below!

Package icon Completed Demo Files54.29 KB
File Demo script16.71 KB
30 Mar 2012

IntelliTrace vs. PreEmptive Analytics


Visual Studio 2010 introduced an amazing feature: IntelliTrace which allows for deep debugging experiences inside Visual Studio by collecting an AMAZING amount of information (basically a stack trace for every call in your code + meta data) and allowing you to use it later to replay the way the application was used. With this feature you could eliminate those “No Repro” bugs! The catch in 2010 was it was NOT allowed to be used in production. In Visual Studio 11 that has changed and we can use it in production: &

PreEmptive Analytics

This change in licensing may seem to put IntelliTrace in direct competition with another great tool, PreEmptive Analytics (PA). I have mentioned this amazing tool before and with Visual Studio 11 it is included “in the box” so there seems to be a conflict brewing – but there isn’t.

Two sides of the same coin

These two tools are both part of the collect information so you can react to it later and fix bugs set of tools, but they have very different use cases. IntelliTrace is specific to the scenario of replaying an application for diagnosis and debugging purposes. It is not meant to be an always on tool and it is a tool that writes to a local file that needs to be collected some how.

PA on the other hand is a tool to always have on, it does capture error information but nothing more than the simple Exception + Stack which is not as useful, detailed or integrated into VS when compared to IntelliTrace. In addition PA allows me to do a lot of a lot of analytics on my application that are not possible in IntelliTrace:

  • what features are people using
  • where in the world are they
  • when are they using it
  • what are their machines like

In addition the PA reports get automatically sent to a server (that they run or that you can run if you have privacy/security concerns) so there is not need to waddle around collecting files.

I can also see scenarios that these two work hand in hand – PreEmptive getting higher level info that shows a lot of users having issue X, then the support guys contact some users and do a more detailed capture of the issue with IntelliTrace.

28 Mar 2012

.NET 4.5 and how it sits in the .NET ecosystem


  • .NET 4.5 – 8th major release.
  • .NET 4.5 is an in place replacement of .NET 4.0.
    • Installing it could cause issues for .NET 4.0, but is very unlikely and likely shows your app is using undocumented features or using features incorrectly.
  • .NET vesions, CLR versions & language versions are not in sync.
  • There is an awesome chart below which makes it easy to see the relationships in the ecosystem.


.NET 4.5 is the next release and it is important to take a look how it fits in the .NET ecosystem. This is the 8th major release of .NET! What do I mean by major release? I mean any release that is not a patch/support only release, or put another way a major release it included major new features in the CLR and/or a new language options.

SxS vs. Replacement

In .NET we are lucky that many versions can run side by side (SxS) provided they have different versions of the CLR, however if a new major release shares the same CLR it is a replacement/additive version. For example: .NET 3.0 used the same CLR as .NET 2.0 (the CLR 2.0) and when installed replaced many of the files in .NET 2.0 with new versions and it is only via compiler directives that some things are turned on and off. The advantage of the SxS model is installing a new version doesn’t influence apps on the previous version in any way (i.e. if the app is 1.1 and works fine before .NET 2.0 was installed, it will keep working fine after .NET 2.0 is installed).

The problem with replacement model is that there is a chance that installing a new version breaks apps on the original version – however Microsoft does a RIDICULOUS number of testing to make sure this doesn’t happen, so that chance is very small. In fact if you happen to hit one, the chance is higher you are using undocumented features or using features incorrectly.

The reason for this explanation of SxS vs. replacement is that .NET 4.5 is an in place replacement for .NET 4.

Version Naming

Part of the confusion I suspect around me saying that .NET 4.5 is the eighth release is because Microsoft naming of versions is about as far from logic as you can get – the worst examples are the .NET Version 3.5 SP 1 is a major release labelled a Service Pack 1?! and the fact we do not have a version 3 of the CLR, it was just skipped?!

The other aspect is that versions of the CLR, versions of the Framework and versions of the languages are completely out of sync, so .NET 4.5 runs on the CLR version 4 and we write code in C# version 5.0 or VB version 11.0 – cause that makes sense :S

Awesome Poster

Here is an awesome poster to help remind you of all the above!


27 Mar 2012

Installing Windows Phone Developer Tools on Windows 8

The joys of being on the bleeding edge, is we are sometimes bleeding such as the fact the Windows Phone Developer tools have not worked on Windows 8… until now. However the steps to do get this working are not easy and are spread out a bit on the Internet, so this post aims to give you a one stop, quick reference way on how to get it done in five steps.

Step 1 – Get the bits

You will need THREE downloads for this:

  1. The Games for Windows Marketplace Client:
  2. The Windows Phone SDK 7.1:

    personally I would get the ISO for it from:

  3. The Windows Phone SDK 7.1.1 Update:

This should set you back 1.1Gb in bandwidth.

Step 2 – Install the Games for Windows Marketplace Client


Troubleshooting notes:

Step 3 – Install .NET Framework 3.5

Now pop in your Windows 8 DVD (or mount the ISO), next open a command prompt AS ADMINISTRATOR and navigate to the \sources\sxs folder on the DVD and run the following command. My DVD was mounted on drive F so note you may need to change the underlined part of the command to match your situation: dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:f:\sources\sxs /LimitAccess


Step 4 – Install Windows Phone SDK 7.1

Now run the installer for the Windows Phone SDK 7.1 as per normal.


Troubleshooting notes:

  • If you get any errors about installing some components, try to copy them from the disk to the desktop – if you get a invalid MS-DOS function error, then you have a corrupt ISO and need to download it all again.

Step 5 – Install Windows Phone SDK update

Almost there, just the Phone SDK update to install!



And there we are, the tiles are on the start screen, Visual Studio 2010 launches (and hurts my eyes with all those colours :P ), the new emulator options are all there in the drop downs and the EMULATOR WORKS!!!!


Troubleshooting notes:

  • If you have a CPU that supports SLAT (for example a Core i7) you can run Hyper-V on Windows 8, which hurts emulator performance. Turn if off it you can.
20 Mar 2012

Windows 8 Bootcamp

windows8logo_large_verge_medium_landscapeLast week (14th March 2012, to be exact) I had a great opportunity to travel to Cape Town and present the first ever Windows 8 Bootcamp there! (I missed the first in South Africa by two days, that was presented in Jo’burg by Rudi Grobler).

It was a small event, but it was a great day of learning and sharing and what a lovely place it was to present, as you can see from the photos below!

One of the requests from those who attended the event was the demos & slides – however there is a snag, Microsoft owns the slides and they are not ready for them to be publically shared Sad smile  That said the demo bits are below, so hopefully that will keep you sorted until the slides arrive.


Package icon Windows 8 Cape Town Camp.zip597.72 KB