As I’ve had occasion to look at more C#/XAML code lately, I’ve noticed a common pattern around the await keyword. Make no mistake: await is a marvelous language construct that makes it super-simple to write code using async APIs that otherwise looks like synchronous code:

private async Task<[type]> MyFunction()
{
String result1 = await Operation1();
String result2 = await Operation2(result1);
processResults(result2);
await Operation3();
return [something];
}

Once EcmaScript6 is adopted in the app host for Windows Store apps written in JavaScript, we’ll see the same thing in that language as well.

What’s important to remember about await, however, is that it’s not always necessary. That is, if you simply need to start an async operation but don’t need its results right away, then you don’t need to stick an await in front of it and block the current thread. That is, you don’t want to force synchronous behavior where it’s not actually necessary, allowing instead for some operations to run in parallel.

In the code snippet above, for instance, we clearly need to wait for Operation1 to finish before invoking Operation2 because we need result1 as input to Operation2. Operation3, however, is not dependent on Operation2 at all, so it can clearly be running while we wait for Operation2 to finish.

In addition, because we’re not returning anything from Operation3, we don’t need to await that one before returning from the function.

Remember that await is just an easy way to avoid writing explicit async structures with an explicit completed handler (as you have to do in JavaScript today), and if you don’t need to do anything with those results, then it’s not necessary to use await at all. (For more background on async and await, see Diving deep with WinRT and await on the Win8 Developer Blog.)

The code above, then could be written as follows to allow Operation2 and Operation3 to run in parallel, along with anything that happens after MyFunction returns:

private async Task<[type]> MyFunction()
{
String result1 = await Operation1();

String asyncOp = Operation2(result1);
asyncOp.Completed = delegate(IAsyncOperation<String> result2, AsyncStatus status)
{
if (status == AsyncStatus.completed)
{
processResults(result2)
}
};

Operation3();
return [something];
}

It’s more code to write, but will generally make for better performance in your app.

 

 



Even though this capability does not exist in WinRT directly, it is possible to determine the processor architecture at runtime through the Win32 API, GetNativeSystemInfo. This API is included in the list of Win32 APIs that can be called from Windows Store apps (see the system page specifically). You can call this directly from a C++ app, of course, and from C# or Visual Basic you can use PInvoke as described on this MSDN forum thread.

To use the API from JavaScript, as with any other Win32 API, you’ll need to create a WinRT component wrapper. I show how to do this in Chapter 16 of my book, with the resulting DLL/WinMD being small. The short of it is that within your JavaScript app project, right click the solution in Visual Studio and select Add > New Project… then choose Visual C++ on the left and Windows Runtime Component in the middle. Call it SysInfo for lack of a better name.

In pch.h, add this line:

#include<Windows.h>

In the component’s header (.h) file, define a method like this:

namespace SysInfo
{
    publicrefclassInfosealed
    {
    public:
        Info();
        static Platform::String^ GetProcessorArchitecture();
    };
}

 

Here’s the implementation of the class in the .cpp file:

#include“pch.h”
#include“Info.h”

usingnamespace SysInfo;
usingnamespace Platform;

Info::Info()
{
}

String^ Info::GetProcessorArchitecture(void)
{
    SYSTEM_INFO sysInfo;
    String^ str;

    GetNativeSystemInfo(&sysInfo);

    switch (sysInfo.wProcessorArchitecture)
    {
        casePROCESSOR_ARCHITECTURE_AMD64:
            str = “x64”; //AMD or Intel
break;

        casePROCESSOR_ARCHITECTURE_ARM:
            str = “ARM”;
            break;

casePROCESSOR_ARCHITECTURE_IA64:
            str = “IA64”;
            break;

        casePROCESSOR_ARCHITECTURE_INTEL:
            str = “x86”;
            break;

        default:
            str = “Unknown”;
            break;
    }

return str;
}

 

To use the component from JavaScript, right click the JS project in Visual Studio and select Add Reference…. In that dialog select Solution on the left and the component name in the middle. Then you can use this line and do what you want with the resulting string.

var arch = SysInfo.Info.getProcessorArchitecture();

You could also return numeric codes from the C++ component, of course…your choice.

 


I wrote about creating WinRT components in C#/VB in Chapter 16 of my book, and you can use such components from JavaScript. However, we’re seeing significant issues with the memory footprint of apps when you have both the JavaScript and the .NET runtime (CLR) loaded in the same process, so we’re recommending developers avoid that situation. Here’s a writeup from my teammate Kyle Marsh:

As Windows 8 has been gaining adoption Microsoft has been gathering more data from participants in our various feedback programs. One thing we observed in this data is pattern of memory usage spikes from Windows Store apps using JavaScript when the apps also use components built with C# or VB.

We know from the data we gather from Windows telemetry that users running multiple apps on less powerful hardware will occasionally encounter situations where the hardware cannot handle all the tasks. When this happens, system performance can degrade rapidly and  a spike in memory usage for apps that mix JavaScript and C# or VB is unavoidable.  Users who have more powerful hardware, or who run very few apps simultaneously, are less likely to be impacted but may still encounter reduced performance in certain situations.

Being conscious of the memory being used in the app can avoid exacerbating the problem, but it will not eliminate it.  Even well written apps will face a significant increase in memory footprint when mixing both JavaScript and C# or VB. We therefore recommend that developers avoid these memory spikes by not mixing JavaScript and C# or VB in their apps.

For developers who to provide components that can be used by JavaScript apps we recommended that you implement components with C++ instead of C# or VB.  C++ apps are compiled ahead of time and run directly on the OS, or in hardware, which every process already loads so there is no additional memory penalty for native code. Providing components in native code also avoids having two execution environments, thus it dramatically reduces the memory footprint and the likelihood of memory usage spikes.


To continue from my previous post, here are some additional performance tools to know about.

First is a JavaScript memory analyzer that was just put out a short time ago. Read about it here: http://blogs.msdn.com/b/visualstudio/archive/2013/01/28/javascript-memory-analysis-for-windows-store-apps-in-visual-studio-2012.aspx

Second, here are topics in docs on performance analysis:

Analyzing performance of Windows Store Apps

Timing and Performance APIs (HTML/JS)

Analyzing memory usages in Windows Store Apps (HTML/JS)

Analyzing the code quality of Windows Store apps with Visual Studio code analysis (C#, VB, C++)

 

Finally, there are two posts on the Windows 8 Developer Blog that are relevant:

How to improve performance in your Metro style app

Tackling performance killers: common performance problems with Metro style apps

 


Along with testing the functionality of your app, it's also important to do performance testing on a variety of machines to make sure that your implementation is flexible enough to handle differences in processor speeds (for work on the UI thread) and GPU capabilities (especially affecting animations and rendering). Testing on different network speeds can also be helpful if you rely on online content–testing on a slow network, for example, can reveal the need to use progress controls in key places of your app (so the user doesn't think it's just hung). It can also help reveal places where you might implement strategies to avoid progress controls altogether, such as caching page content or switching between pages just with changes in visibility and not tearing down and rebuilding pages each time.

In any case, I wanted to provide some links to resources over a few posts. Here are a few topics in the docs for starters:

Performance (Windows Store Apps) – all languages

General Best Practices for Performance – all languages

Performance Best Practices – JavaScript

Performance Best Practices – C++, C#, VB, XAML

You'll also want to look at Tool: Performance Analyzer (JavaScript), which is one of the key tools to use for this task.

More to come later on–this is probably enough for you to chew on at present!

 


A long time ago this question came up within my team at Microsoft, long before we did any public disclosure of the new system. Before Windows 8, there was really only one choice to write a native app without taking a dependency on an external framework or other middleware of some kind: C++ (or C) with UI layers like WinForms or DirectX. Windows 8, however, introduced other choices for native Windows Store apps, by which I mean one that has direct access to the system's API without relying on middleware to expose it (and thus require that middleware to be updated to take advantage of new system features). Those choices include using JavaScript with HTML/CSS as the presentation layer; using C#, Visual Basic, or C++ with XAML as the presentation layer; or going the C++ and DirectX route.

Early on, I remember people saying "Of course, JavaScript is the easiest language, so that would typically the natural choice." Well, JavaScript might be more forgiving in the beginning, and perhaps easier to get started with because of the lack of strong data types, but it soon becomes somewhat odd. For example, dealing with async APIs through promises involves a lot more code (and concern about closures) than using the await keyword in C#/VB. Furthermore, writing an app isn't just about the language, it's also about the presentation layer. Here, if you don't already know HTML and CSS reasonably well, you end up having two different specs with different syntaxes and different paradigms. Is that's necessarily easier? I commented a number of times that no one seems to have written book like  Crockford's JavaScript: The Good Parts for C# or XAML because the bad parts have already been expunged!

There are, of course, a few reasons why you might be forced to use one language/presentation choice over another. Protecting intellectual property is best done in C++, though not foolproof–and for that you can use a mixed-language approach to put more sensitive code into WinRT components written in C++. (It does also seem that better obfuscators for JavaScript are coming along…more on that another time.)

If raw graphics performance is a concern for your app, then going C++/DirectX ends up being your only real choice. Many kinds of apps can be effectively written in the other languages, but in the end, if perf totally matters to you, make the choice early to bypass any extra rendering layers you can (i.e. HTML/CSS and XAML). The team that created the FreshPaint app, for example, did this very early on as they had already implemented their paint/texture physics engine in C++/DirectX so there wasn't any reason to think to use a different language for the rest of the app's structures.

Similarly, if you really need to do multi-threaded work, you'll find that easier to manage all that in C++ and the APIs it has to offer. Trying to do the same with JavaScript workers probably won't give the results you want. C#/VB might work well too depending on your needs, but again, with a mixed-language approach you can put certain parts in components written in C#/VB or C++ and perhaps do outer app framework in HTML/CSS (assuming you don't need to share drawing surfaces, which can't be done from JS at present).

One potential advantage of HTML/CSS/JS is that you can write code that's more portable to other platforms where HTML-based options are available, including the web. This does require that you keep Windows-specific code isolate, in the way that tools like Phonegap/Cordova do, but it's possible. (Not that the Windows Library for JavaScript, WinJS, is already portable–it will use WinRT if it's available, otherwise it uses HTML5 APIs.) That said, options like Xamarin (for C#/XMAL) and Unity (for DirectX/C++) give you similar cross-platform approaches for the other languages.

There are a few cases where Windows 8 doesn't have exact parity between HTML/CSS and XAML, where HTML/CSS has a couple more controls. On the flip side, if you're trying to directly incorporate web content into an app, you have to use an HTML iframe if the content needs HTML5 capabilities like AppCache or LocalStorage, but then if the web site has frame-busting code, you have to use the x-ms-webview element which doesn't have all the HTML5 goodies, which also goes for the The XAML WebView. Clearly this is an area that can be improved, but for now, it's good to know that these limitations can make-or-break your language decision.

Clearly, if you have existing code in one language or another, then it makes sense to reuse much of that instead of porting it to another language. Once more, this is where a mixed-language approach comes into play.

All in all, the more we discussed this question amongst ourselves, the more we realized that there never really was a set answer for any given developer. We drafted a number of papers to try to spell out the strengths and weaknesses of each choice, but in the end, I whittled it down to these thoughts:

  1. If you already know one of the languages/presentation layers and not the others, and don't have a specific issue that would force you into a choice, then stick with what you know. Otherwise you'll have to face a big learning curve.
  2. If you know more than one of the languages/presentation layers already, then you don't need Microsoft to spell out the strengths and weaknesses: you understand those already and can make an intelligent choice.
  3. If you don't know any of them, then you should spend a couple hours working through the basic tutorials of the Windows Developer Center (the "Developing Apps" topics listed here), and see which one you like the best. I have generally figured that those coming from Java and Objective-C would probably pick up C# (or maybe C++) easier than learning the semi-mystical tones of CSS, whereas a web developer would typically find HTML/JS a familiar territory.

I was very glad, in fact, to see that the banners at //Build 2011 in Anaheim were emblazoned with the words "use what you know" where writing apps was concerned. An in working with partners building apps over the last year, that's pretty much played out to be the right way to approach the matter.

 


As described in Chapter 16 of Programming Windows 8 Apps in HTML, CSS, and JavaScript, Visual Studio can only debug one type of code at a time. Here’s the relevant excerpt:

When you hit that [JavaScript] breakpoint, step through the code using Visual Studio’s Step Into feature (F11 or Debug > Step Into). Notice that you do not step into the C# code, an effect of the fact that Visual Studio can debug either script or managed (C#)/native (C++) code in one debugging session but unfortunately not both. Clearly, using some console output will be your friend with such a limitation.

To set the debug mode, right-click your app project in solution explorer, select Debugging on the left, and then choose a Debugger Type on the right as shown in Figure 16-3. For debugging C#, select Managed Only or Mixed (Managed and Native). Then set breakpoints in your component code and restart the app (you have to restart for this change to take effect). When you trigger calls to the component from JavaScript, you’ll hit those component breakpoints.

Fortunately, there is a way to debug both types of code at the same time using two instances of Visual Studio:

  1. Launch the app (F5) with Script Only debugging selected. This is the instance of Visual Studio in which you’ll be stepping through JavaScript.
  2. Load the project in a second instance of Visual Studio. Ignore warnings about IntelliSense files being already open, but prepare to wait a little while as VS will build a new copy of that database for this second instance.
  3. In this second instance, set the debugging mode to Native Only, Managed Only, or Mixed, depending on your needs. This is where you’ll be debugging C#/VB/C++ code, as in a WinRT component.
  4. Select the Debug -> Attach to Process… menu command. (You do this instead of running the app a second time.)
  5. Find and select the line for WWAHost.exe in the process list that has your app name in the title column.
  6. Above the list, check the Attach to value. If it says “Automatic: Script code”, press the Select… button and indicate Managed and Native instead. Close that dialog.
  7. Click the Attach button.

Then go set breakpoints in this second instance of VS where you want to step through managed/native code. While this still won’t allow you to step across the language boundaries in a single debugger, it will allow you to step through each code type in the different instances.

Thanks for Rob Paveza for this tip.