Controlling actual Thread Priority in WinRT and Windows Phone

By jay at February 18, 2014 19:58 Tags: , , , ,

tl;dr: Setting the WorkItemPriority in ThreadPool.RunAsync actually changes the thread priority the code runs on, not just the position in the pending work queue.

It’s been a while since I’ve blogged, but this entry has been a finding that had long eluded me and this was a good chance to blog again. If you’re still reading, thanks :)

 

In the Plain Old (or might I say, complete) .NET framework, there was a pretty useful property named Thread.Priority, which gave a lot of control to app developers. This allowed a very control of what would run, where, and how.

Using this API, you could have CPU bound (hence blocking) code that could run at a very low priority, without the need to be yielded somehow, like it’s suggested now with async and Task.Yield().

 

I was under the impression, since Windows Phone 8.0 and WinRT 8.0 have been introduced, that there was no available way to control the actual thread priority, since either the property does not exist, or even Thread does not exist anymore.

The suggested counterpart, Task, does not provide such a feature, leaving developers no choice but chunking the work, by using clever tricks or work item priority scheduling.

 

More...

Building in Parallel Across Multiple Build Agents in TFS2012 for Metro Apps

By jay at March 30, 2013 12:50 Tags: , , , , , , ,

TL;DR: Using an upgraded (and fixed) Parallel Build Process Template allows to use multiple TFS2012 build agents simultaneously, which can be more than welcome when building metro apps that target all three supported platforms. A build that took 11 minutes can go down to 3.5 minutes.

Download the Parallel Build Process Template for TFS2012 here.

 

CI is a wonderful feature, especially when associated with Gated Checkins.

You’re certain that what’s in your source control is in line with your build definition and constraints, and that there is always a binary that respects a minimum set of rules. This does not ensure that your app is bug free, but still, that’s a minimum.

 

Build time matters

The downside of this validation is that there cannot be multiple builds running at the same time. This can become a bottleneck when multiple developers checkin within the duration of a single build run.

This means that the longer your build gets, the longer a developer might wait for its task completion because of a long build queue, and increase its task switching cost. If a build fails, the developer needs to unshelve its changes, make the necessary adjustments, then check-in again.

Below 4 minutes of build time, this stays in the acceptable range where the developer’s task context may not be lost if the build fails.

More...

Writing a Xaml attached property in C++/CX to resize Images, with a Performance twist

By jay at February 04, 2013 21:41 Tags: , , , , , ,

TL;DR: Writing Xaml/C++ attached properties sometimes gives a 30% improvement over the C# version, which can be caused by the use of events. This article shows code sample for both versions.

 

 

Since it is possible to write a XAML application entirely in C++/CX, I decided to give a try to the performance of some simple code.

There is, after all, some marshaling involved when communicating from C# to native code, particularly with events.

 

The ImageDecodeSizeBehavior

WinRT’s BitmapImage class supports, as does WPF and Silverlight, the DecodePixelWidth and DecodePixelHeight properties.

These are very useful properties that forces the memory surface to store the image to fit a certain size, and avoid the waste of memory induced by large downscaled images. This is a very common performance issue for applications that display variable sized images, where the memory can grow very quickly.

More...

On the Performance of WinRT/Xaml Template Expansion

By jay at February 02, 2013 15:11 Tags: , , , , , ,

TL;DR: Expanding data-bound item templates in Xaml/WinRT in Windows 8 is about a hundred times slower than with Xaml/WPF. This article details how this was measured and a possible explanation.

 

In Windows 8, Microsoft has a introduced a whole new Xaml stack, codenamed Jupiter, completely re-written to be native only.

This allows the creation of Xaml controls using C++ as well as C#.

I will not discuss the philosophical choice of ditching managed WPF in favor of a native rewrite, but make a simple comparison of the performance between the two.

 

Template Expansion Performance

I worked on a project that had performance issues for a UI-Virtualized control, where the initial binding of data as well as the realization of item templates, was having a significant impact on the fluidity of the scrolling of a GridView control.

To isolate this, I created a simple UI: More...

DataBinding performance in WinRT and the Bindable attribute

By jay at November 26, 2012 20:51 Tags: , , , ,

tl;dr: The Bindable attribute can be placed on standard C# classes in Metro Apps to make them appear in the generated IXamlMetadataProvider class, to create static metadata. This technique allows for a 10% increase in data-binding performance over reflection based binding, but also adds a temporary cost in JITting, until Windows generates native images 24 hours later.

Databinding in WPF/WinRT is very easy to use. Just put the name of the field you want to bind, set the DataContext, and voila, it is displayed on screen. Yet, this is a tricky feature under the hood. It relies on the presence of an arbitrary string that may exist in the current DataContext to get the data to be displayed.

In WPF and Silverlight, this is fairly easy to do because everything is in managed code. Resolving that data member was performed using a bit of type Reflection, where the string "{Binding SomeValue}" would result in a sequence of Type.GetProperty to get a PropertyInfo instance, then call GetValue to get the actual value.

But in WinRT, all this is a lot different, mainly because WinRT is purely native and there is no reflection or metadata there.

More...

Reducing apps startup time with Pre-JITing and NGEN on a Surface RT

By jay at November 24, 2012 21:13 Tags: , , , , ,

TL;DR: The JIT can take over a third of the startup time of a managed Metro App, and using Native Image Generation (NGEN) can greatly improve the startup time of these apps. There is also a way to check for these native images to act accordingly.

 

A while back, I’ve had the chance to work with the guys that are behind the Pre-JIT feature of the CLR 4.5 for Metro Apps. Back then, I was only able to work on x86/x64 architectures, as ARM/Windows RT devices were not available.

Now that the Surface RT devices are available, we’re facing quite a few challenges in terms of code execution performance, and I’m going to discuss a few tips and tricks about the Managed Code JIT on Windows RT.

 

Profiling a slow starting app on a Surface RT

Running apps on the Surface can be troubling. Having an app that is useable after 16 to 18 seconds is definitely not acceptable, let alone the fact that the Splash Screen can disappear after 6 to 8 seconds.

Profiling such an app that starts slowly is very interesting, when looking a the Visual Studio profiler, where during these 17 seconds, about a third is spent in a “clr.dll” module in exclusive time (time spent only in this module and not its descendants). This is a very big number.

This time is actually spent in the JIT, where big methods tend to take more time to be JITed, sometimes on the UI thread, making the app sluggish.

More...

Of Static Code Analysis, CA0001, WinMD files and C# Dynamic in Metro Style apps

By jay at October 27, 2012 12:42 Tags: , , , ,

tl;dr: This article is about working around an FxCop internal bug using the C# dynamic keyword, not exactly the way is was supposed to be used.

 

With the release of Windows 8 and WinRT, developing in .NET requires adding references to the new WinMD file format.

This format is a .NET assembly look-alike, so look-alike that old ILDASM builds can open them.

These files are only containing stubs, the definition of types that come from WinRT, which is developed using native C++ code.

 

WinMD files and Static Code Analysis

FxCop is working rather fine with WinMD files in Metro style apps, except for one interest case, when compiling the following code :

private static void SomeMethod()
{
   var b = new Button();
   b.Command = null;
}

Which fails with the following exception when analyzed by FxCop, using the “Microsoft Managed Recommended Rules”:

CA0001 : Rule=Microsoft.Reliability#CA2002, Target=App.MainPage.#SomeMethod() : The following error was encountered while reading module 'App3': Could not resolve member reference: [Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null] Windows.UI.Xaml.Controls.Primitives.ButtonBase::put_Command.

The reason for this is rather obscure though. It seems that FxCop is trying to analyse the declarative security attributes of WinMD exposed methods, but fails to do so… Which is ironic since these attributes cannot be used in Metro style apps :) But still, this is a multi-framework analysis engine.

Unfortunately, there seem to be no way to put an ignore directive, or supression attribute for this kind of internal error so fixing this, until this gets resolved by Microsoft, requires a bit of a hack.

 

A CA0001 workaround and the Dynamic keyword

The problem here is that FxCop tries to analyze the code, and finds the put_Command() method and tries to analyse it. The goal here is to get the code compiled and executable, while having FxCop ignore it.

Here’s how to do it :

private static void SomeMethod()
{
   #if DEBUG
   var b = new Button();
   #else
   dynamic b = new Button();
   #endif

   b.Command = null;
}

I do agree with you, really. This is not a particularly pretty code, and may not be that fast to execute, but it does the trick to still have Static Code Analysis running to catch all other possible code issues.

Having a dynamic variable in Release configuration, where FxCop is executed, allows to hide the call to put_Command() as a string generated by the C# compiler, while maintaining it original meaning.

Here's what actually generated by the compiler, to evade FxCop scrutiny :

object b = new Button();
if (MainPage.o__SiteContainer0.<>p__Site1 == null)
{
   MainPage.o__SiteContainer0.<>p__Site1 = CallSite>.Create(Binder.SetMember(CSharpBinderFlags.None, "Command", typeof(MainPage), new CSharpArgumentInfo[]
   {
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), 
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null)
   }));
}
MainPage.o__SiteContainer0.<>p__Site1.Target(MainPage.o__SiteContainer0.<>p__Site1, b, null);

Having the code compiling using an actual static typing in Debug configuration leaves a bit of compile-time type checking, nonetheless.

There should be a connect entry for this soon, if you'd like to follow-up.

Happing dynamic hacking ! :)

C# Async Tips and Tricks, Part 3: Tasks and the Synchronization Context

By jay at September 29, 2012 21:12 Tags: , , , , , , , ,

TL;DR: It is possible to mix C# async and basic TPL style programming, but when doing so, the synchronization context capture feature of C# async is not forwarded to TPL continuations automatically, making UI dependent (and others) code fail and raise exceptions. This can lead to the termination of the process when exceptions are not handled properly, particularly in WinRT/C# apps.

 

I’ve discussed in a previous article of this series, the relation between async Task/Void methods and the ambient SynchronizationContext.

Just as a simple reminder, when executing a async method, whether it is Task, Task<T> or Void returning, the caller’s SynchronizationContext is captured to ensure that all the code in an async method is executed in the same context. The main scenario for this is to easily execute UI bound code in an async method.

It is important to remember that async methods are based on the TPL framework, and that async methods (except in infamous async void) return System.Threading.Tasks.Task instances.

More...

Windows 8, Developers, Hyper-V and the new VHDX format

By jay at July 13, 2012 22:03 Tags:

TL;DR: Windows 8 added support for SSD TRIM commands in its VHDX format, making very easy to boot from a virtual drive on an SSD drive. This allows to never install Windows directly on a physical disk anymore, easing backups, cloning and virtualization. It also allows for very easy migration between different versions of Windows 8.

It's been a very interesting year with Windows 8. We've been fed with two new releases since the Build conference, the Consumer Preview and Release Preview, and now it's the RTM that's coming along in August.

With all these releases to play with, it's a game of install, re-install and co-existence of multiple windows instances on my machine.

I do not like losing to much time staring at my computer while it reinstalls everything from scratch, particularly Visual Studio, and both booting a physical machine from VHD and/or virtualizing it Hyper-V has been very helpful to save time.

More...

C# Async Tips and Tricks Part 2 : Async Void

By jay at July 08, 2012 17:05 Tags: , , , , , , ,

TL;DR: This article discusses the differences between async Task and async void, and how async void methods and async void lambdas, used outside the DispatcherSynchronizationContext, can crash the process if exceptions are not handled.

You can also read the part 3, Tasks and the Synchronization Context.

In the first part of the series, we discussed the behavior of async methods. The second part discusses how async Task and async void methods can differ in behavior, while seemingly being similar.

 

Authoring Async Methods

Async methods can be authored in three different ways:

async Task MyMethod() { }

which creates a method that can be awaited, but does not return any value,

async Task<T> MyReturningMethod { return default(T); }

which creates a method that can be awaited, and returns a value of the type T,

async void MyFireAndForgetMethod() { }

which is allows for fire and forget methods, and cannot be awaited.

You may be wondering why there are two ways to declare a void returning method. Read on.

More...

About me

My name is Jerome Laban, I am a Software Architect, C# MVP and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Remote Control for Windows Phone.