Sunday, March 01, 2015

Async Await By Example - Part 1

When I first started using C#’s async/await keywords I found it helpful to create a set of notes as I progressed.  On this post you’ll find a collection of tips and how-tos.  Hopefully others will find it useful.

Quick Tips

* Each managed thread in .NET reserves around 1MB of virtual memory
* Only a method marked async can contain the await keywords

Using NUnit to Run Test Methods

I’m using NUnit as a convenience to step through my test code.  As of v2.6.2, NUnit supports unit tests with the async keyword. 


 Beginning with NUnit 2.6.2, test methods targetting .Net 4.5 may be marked as async and NUnit will wait for the method to complete before recording the result and moving on to the next test.Async test methods may return void or Task if no value is returned, or Task<T> if a value of type T is returned.

Thursday, February 26, 2015

Using ImportMany For Lazy Initialisation With Reactive Extensions (RX) and WPF/Prism




Working on a WPF application, I had a requirement to allow a user to monitor the status of a number of connected services – the status of some services could fluctuate many times per second.


There were a couple of issues that needed to be considered:

  1. How would I get hold of these monitored ‘services’?  Could I just create new instances and pass them into my monitoring class?  Unfortunately not, as I didn’t know until runtime what these services were.
     
  2. How would I throttle the status updates to make them more presentable to the user without resulting in some sort of flashing Christmas tree effect?
      
  3. How would I unit test the monitoring behaviour?
     
  4. How would I display the status of specific items in an easy to understand manner?  Did I want to wait for a disconnect status and show that in, say, red? 

Tuesday, February 10, 2015

How Slow is Repeatedly Parsing an Expression for INotifyPropertyChanged

Introduced in .NET Framework v4.5 (as a C# 5.0 compiler feature), the CallerMemberNameAttribute allows you to determine the method or property name of the caller of a method.

This comes in very handy if you’re adding logging code, or in the case of with WPF you’re using models based on the INotifyPropertyChanged interface, where you need to fire the PropertyChanged event passing along the name of the property that’s changed.

Prior to the availability of CallerMemberName, you had a couple of choices when calling the PropertyChanged event:

  1. Pass a hard-coded string to identify the property name.
    This has clear drawbacks – what if the property name changes/identifying code dependent on the property?
     
  2. Parsing an expression tree that represents a concrete class property
    Handy, because you’re referring to a class's property  


There are plenty of examples available showing how to parse an expression tree (see below), but be very careful, parsing an expression tree is very, very slow compared to using the CallerMemberName or passing in a string to identify the property. 

Sunday, February 08, 2015

Improving Struct Performance By Overriding GetHashCode()

In an earlier post, I discussed the pitfall of using structs in C# to store data and failing to override the Equals method.  In this post I’ll look at the GetHashCode method and how not overriding the default implementation can have a drastic effect on the performance of a C# application.

I was asked by a client to investigate the performance of a C# WPF application; users were concerned that performance across certain areas just didn’t feel as fast as it ought to be – particularly during busy times of a trading day.  

After analysing the code and using an automated profile application (ANTS by Red Gate) I narrowed down the bottle neck to a struct had been used to store stock market prices.

Improving Struct Performance By Overriding Equals()

I’ve spent a few days analysing the performance of a C# WPF application.  The client’s users were concerned that performance across certain areas just didn’t feel as fast as it ought to be – particularly during busy times of a trading day. 

That might sound pretty vague, but often as developers that’s all we get.

There are plenty of resources available that go into a great level of detail on the best practices to follow when designing apps.  It helps to understand what .NET does under the hood, in many aspects, but it’s important to remember that there are many layers in which subtle coding designs can negatively affect performance.

I’m going to describe some interesting implementation details which I discovered were the cause of performance issues that the users were complaining about.  This particular blog covers structs and how slow Equals calls can be – please see my other blog entry for similar results found by examining the default GetHashCode implementation.

Sunday, February 01, 2015

Adding Template Classes to Visual Studio 2013's "Add New Item" Screen (NUnit Test Class)

When using Visual Studio,  if you follow Test Driven Development principles, then you're probably used to repeatedly following these steps when adding a new test class (using NUnit as an example):

  1. Right click on Solution Explorer
  2. Click Add  and then New Item
  3. Selecting Class from the list of items
  4. Entering your test class name
  5. Typing in or pasting similar looking lines of code:

using System;
using NUnit.Framework;
 
namespace MyProject
{
    [TestFixture]
    public class MyTestClass
    {
 
        [Test]
        public void Test()
        {
        }
 
    }
}

Wednesday, January 28, 2015

Performance Testing Framework




In this post I’ll introduce a set of performance testing classes and practices that I use when creating automated performance tests – with one main aim: simplify the task of measuring/verifying the performance of key areas of my .NET applications.

Source Code:
 

Often it is not practical, nor even recommended to measure all parts of an application – why waste time profiling sections of code that get called infrequently?  It’s also rather difficult knowing exactly where to start profiling an application, whether it’s server or UI, when that app either hasn’t had performance proactively “baked in” or when you’re trying to find the root cause of an occasional freeze. 

If I’m trying to isolate performance issues (or maybe retrofitting performance tests), then I tend to start off by using any of the popular . NET profiling apps, such as Red Gate’s ANTS.   These give me an idea of where to look, eg for methods that are called very frequently or take a while to run.  At least this gives me a fighting chance of where to concentrate my efforts, rather than wading through 1000s of lines of code…needle in a hay stack springs to mind.

There are many resources available showing common coding pitfalls, which can result in extra memory allocates that aren’t needed, making non-deterministic functions behave in a deterministic fashion, lack of caching, multiple enumerations etc.  Such examples include:
  • string concatenation rather than using a StringBuilder, 
  • switch versus multiple if statements, 
  • caching values for ToString/GetHashCode on immutable types

Friday, January 23, 2015

Displaying Colour Coded Percentage Columns in WPF XamDataGrid

Infragistic's XamDataGrid is a highly customisable WPF control.

I'm going to walk through the steps required to display a number of colour-coded fields on a XamDataGrid, where each field is bound to an underlying percentage based property.  

This is achieved by binding a Brush instance to the Background property of the Field's CellValuePresenter:


Detecting Binding Errors - WPF PresentationTraceSources.DataBindingSource

By default, Visual Studio (v2012 onwards) is configured to automatically log any binding errors detected whilst running a WPF application.

You can see examples of such in the Debug Output window:
System.Windows.Data Error: 40 : BindingExpression path error: 'MyUnknownProperty' property not found on 'object' ''Product' (HashCode=30581329)'. BindingExpression:Path=MyUnknownProperty; DataItem='Product' (HashCode=30581329); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')
This setting can be adjusted using the Debugging, Output Window settings: 



Often, it's useful to be notified in a more intrusive manner when a binding error has been detected...rather than silently continuing, just as WPF does.

In order to add your own handling, you need to add a class that derives from TraceListener to the PresentationTraceSources.DataBindingSource.Listeners collection.

Wednesday, January 21, 2015

WPF Frame Rate Calculator

I've been playing around with WPF's CompositionTarget.Rendering event.
From the documentation:

CompositionTarget.Rendering Occurs just before the objects in the composition tree are rendered.The Rendering event is routed to the specified event handler after animation and layout have been applied to the composition tree.
From this event, I've been looked at a way to calculate how many frames are being rendered per second in a WPF application.

Caveat Emptor:
  1. CompositionTarget.Rendering is a static member, so remember to unhook your delegate when you don't need it...leaks....
  2. The act of adding a delegate to CompositionTarget.Rendering might slow your WPF application down...so it's probably best used debugging performance, or as a user configurable options when used in a production environment.  
  3. My calculations aren't very scientific..but the numbers produced are close to those seen by attaching to the application with Perforator from WPF Performance Suite.
This could be handy if a low frame rate is detected, you could log the time stamp (using something like log4net) and compare what was going on in the rest of you app.

Sunday, January 18, 2015

Code Block/Scope Timing Snippet

You've got users complaining that it takes too long for a screen to open or for a certain piece of code to run.  Wouldn't it be handy to wrap the execution of a key block of code with some timing statistics?


The following TimeIt class is derived from IDisposable which makes it easy to wrap a code block (aka scope) with the using keyword (this will ensure that if any exceptions are raised you'll still get to final end scope logged).

The timing internals are hidden way - it's easily accessed via a static Log method:

using (TimeIt.Log("Calculate cost"))
{
    Debug.WriteLine("Retrieving price..");
    var price = pricingService.GetPrice();
    var cost = notionalCalculator.GetUSDValue(price);
}

Wednesday, January 14, 2015

Using RefCount To Create Automatic Disposal and Lazy Connections

This is quite a common scenario, I need to create a source data provider from some type of 'expensive' service, eg a stock market price ticker, which will automatically handle the job of connecting and disconnecting as the number of active observers changes.

By 'expensive' we could mean resource-wise expensive, ie amount of memory/ cpu time or financially expensive...perhaps there's a charge levied per subscription.

As an example, let's say you have a trading application with the following requirements:
  • User can open any number of trade entry screens.  
  • The trade entry screen allows the user to enter a stock symbol, eg MSFT
  • Once a symbol has been entered the application should subscribe to a market data source, eg Reuters, for that symbol and display the current price
  • If multiple screens request the same symbol then only one underlying subscription should be utilised - don't go creating yet another subscription for the same symbol
  • When a screen is closed or another symbol is selected, then we should notified when there no longer any active subscribers, thus allowing us to release the underlying source subscription
  • Subsequent requests to an already subscribed symbol should immediately send back the latest price received rather than wait until a new price arrives.