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...

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...

An RxJS to Rx.NET bridge

By jay at January 22, 2013 21:19 Tags: , , , , ,

tl;dr: JavaScript can call C# code in Metro apps, and allows for C# code to observe notifications coming from JavaScript, using the Reactive Extensions grammar.

Javascript is (almost) everywhere, literally.

Not in everyone's minds though, which is only around 7% according to the PYPL index.

Yet, Microsoft is pushing a lot on that front, particularly in Metro apps where the documentation shows JavaScript examples first. Subjectively, I’m not a big fan of the decision, because it pushes us back a few years and not simply because of the language, but because state of the full JavaScript ecosystem, compared to the .NET counterpart.

More...

Reading the content of the Xap/Appx and IsoStore in Windows [Phone] 8

By jay at December 20, 2012 09:57 Tags: , , ,

In Windows Phone 8, things got better of the front of reading the file system. It’s actually gotten closer to the Windows 8 with the inclusion of WinRT, and it now possible to read the content of files that were pretty hard (or impossible) to access directly before.

 

Reading the app package content files

There are some times when you need to access the content of the xap directly, and in Windows Phone 7, you were pretty limited to the use of the IsolatedStorage, but really did not have access to the content of the Xap, except for some location such as images or XmlDocument and the SQL CE engine using the appdata:/ scheme.

Things have changed in Windows Phone 8, and here’s how to read the WMAppManifest.xml file by yourself :

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...

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 ! :)

Implementing an asynchronous settings service, Part 2 : Writing a setting

By jay at October 08, 2012 20:12 Tags: , , , , ,

tl;dr: This article is the second of a series talking about the implementation of an async user Settings Service, using the C# async keyword. This part talks about writing new settings values, asynchronously and the challenges associated with it.

 

In this continuing implementation of a Settings Service series, I'll continue with the addition new features to the service.

Part one talked about reading the settings asynchronously, and this time, we'll talk about writing user settings new values.

 

Writing to the Settings Service

Now let's say that the user has selected a new temperature unit in a weather app, writing a new value to the settings service takes a few more lines, More...

Implementing an asynchronous settings service, Part 1 : Going Async

By jay at October 07, 2012 21:32 Tags: , , , , ,

TL;DR: This article is part of a series about implementing asynchronous services contract, and starts by an the creation of basic functionality for a User Settings storage service using C# 5.0 async features. In the next episode, we'll talk about writing a user setting and consuming settings change notifications.

 

Most applications require the storage of user settings, such as the login, authentication token, preferences, you name it. All these settings have been stored in many locations over the years, such ini files, AppSettings, IsolatedStorageSettings in Silverlight and more recently in RoamingStorage or LocalStorage in WinRT, etc…

Most of the time, this is pretty much CRUD-like contracts that do not offer much to perform asynchronous reading/writing, easy two-way data-binding and notifications. Some offer change notifications, but most of the time, this is related to roaming settings that have been updated.

Reading settings in a synchronous way is a common performance issue, and most of the time accessing the data can be expensive, which is not good for the user experience. For instance, the Silverlight and Windows Phone IsolatedStorageSettings implementation has a pretty big performance hit during the first access, due to the internal use of Xml Serialization (and its heavy use of reflection). It also requires to be synchronized during persistence, and its persistence takes a lot of time too, suspending simultaneous read or write operations.

In this article, I’m going to discuss an implementation of a service that abstracts the use of application or users settings using the C# async/await keywords.

More...

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...

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.