﻿<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  <channel>
    <title>Jérôme Laban</title>
    <description>.NET Powered</description>
    <link>http://jaylee.org/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 2.5.0.6</generator>
    <language>en-US</language>
    <blogChannel:blogRoll>http://jaylee.org/opml.axd</blogChannel:blogRoll>
    <blogChannel:blink>http://www.jaylee.org/syndication.axd</blogChannel:blink>
    <dc:creator>Jérôme Laban</dc:creator>
    <dc:title>Jérôme Laban</dc:title>
    <geo:lat>0.000000</geo:lat>
    <geo:long>0.000000</geo:long>
    <item>
      <title>Controlling actual Thread Priority in WinRT and Windows Phone</title>
      <description>&lt;p&gt;&lt;em&gt;tl;dr: Setting the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.system.threading.workitempriority"&gt;WorkItemPriority&lt;/a&gt; in &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230594"&gt;ThreadPool.RunAsync&lt;/a&gt; actually changes the thread priority the code runs on, not just the position in the pending work queue.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;It&amp;rsquo;s been a while since I&amp;rsquo;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&amp;rsquo;re still reading, thanks :)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In the Plain Old (or might I say, complete) .NET framework, there was a pretty useful property named &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.priority(v=vs.110).aspx"&gt;Thread.Priority&lt;/a&gt;, which gave a lot of control to app developers. This allowed a very control of what would run, where, and how.&lt;/p&gt;
&lt;p&gt;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&amp;rsquo;s suggested now with async and &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.yield(v=vs.110).aspx"&gt;Task.Yield()&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;The suggested counterpart, Task, does not provide such a feature, leaving developers no choice but chunking the work, by using &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2010/04/09/9990424.aspx"&gt;clever tricks or work item priority scheduling&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;A hidden gem&lt;/h2&gt;
&lt;p&gt;In WinRT 8.0+ and Windows Phone 8.0, there is one API, &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230594"&gt;ThreadPool.RunAsync&lt;/a&gt;, which is very similar to .NET&amp;rsquo;s own thread pool, but provides an additional parameter, a &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.system.threading.workitempriority"&gt;WorkItemPriority&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Intuitively, and knowing&amp;nbsp;historically&amp;nbsp;how thread pools work, and that they are supposed to work with relatively small units of work, I thought &amp;ldquo;Ok, yet another API that will prioritize a work queue&amp;hellip;&amp;rdquo;.&lt;/p&gt;
&lt;p&gt;I could not be more wrong!&lt;/p&gt;
&lt;p&gt;This API not only schedules in the queue using the work item priority, but also executes the work item with the specified thread priority !&lt;/p&gt;
&lt;p&gt;To demonstrate the feature, here&amp;rsquo;s a simple code sample :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;private void Profile()
{
   ThreadPool
      .RunAsync(_ =&amp;gt; Run(s =&amp;gt; textbox1.Text = s), WorkItemPriority.Low);
   ThreadPool
      .RunAsync(_ =&amp;gt; Run(s =&amp;gt; textbox2.Text = s), WorkItemPriority.Normal);
   ThreadPool
      .RunAsync(_ =&amp;gt; Run(s =&amp;gt; textbox3.Text = s), WorkItemPriority.High);
}

private void Run(Actiondisplay)
{
	for (int i = 0; i &amp;lt; int.MaxValue; i++)
	{
		i.ToString(); // Slow things down a litthe bit...
				
		if((i % 100000) == 0)
		{
			Dispatcher.BeginInvoke(() =&amp;gt; display(i.ToString()));
		}
	}
}&lt;/pre&gt;
&lt;p&gt;The result is that after a few seconds, the higher the priority, the higher the number displayed on the screen.&lt;/p&gt;
&lt;p&gt;Needless to say, this changes quite a bit of things, where it is definitely possible to having background threads that impact a lot less the dispatcher, even if they are 100% loaded. Good for the UI, good for the user.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s it for now, happy threading !&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2014/02/18/Controlling-actual-Thread-Priority-in-WinRT-and-Windows-Phone.aspx</link>
      <comments>http://jaylee.org/post/2014/02/18/Controlling-actual-Thread-Priority-in-WinRT-and-Windows-Phone.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=ec5857c2-1396-46c3-b67f-9fa81e7384f4</guid>
      <pubDate>Tue, 18 Feb 2014 19:58:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <category>Windows Phone Dev</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=ec5857c2-1396-46c3-b67f-9fa81e7384f4</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=ec5857c2-1396-46c3-b67f-9fa81e7384f4</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2014/02/18/Controlling-actual-Thread-Priority-in-WinRT-and-Windows-Phone.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=ec5857c2-1396-46c3-b67f-9fa81e7384f4</wfw:commentRss>
    </item>
    <item>
      <title>Immutable Data and Memoization in C#, Part 2</title>
      <description>&lt;p&gt;&lt;em&gt;tl;dr: Memoization can be associated with the &lt;a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx"&gt;ConditionalWeakTable&lt;/a&gt;&amp;nbsp;class, which allows the addition of memoized computation results to immutable types. This makes the memoized results live as long as the instances that was used to create it.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.jaylee.org/post/2013/04/18/Memoization-and-Immutable-data-in-CSharp-Part-1.aspx"&gt;In the first part of this article&lt;/a&gt;, we discussed a bit the Memoization pattern in C#. In this second part, we will discuss how to alleviate the memory management issue for memoized computation results.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;ConditionalWeakDictionary to the rescue&lt;/h2&gt;
&lt;p&gt;In .NET 4.0 &amp;ndash; quite a while ago now&amp;nbsp;&amp;ndash; a new class was added, the &lt;a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx"&gt;ConditionalWeakTable&lt;/a&gt;,&amp;nbsp;to help in the creation of dynamic languages based on the &lt;a href="http://msdn.microsoft.com/en-us/library/dd233052.aspx"&gt;DLR&lt;/a&gt;, where there was a need to be able to attach data to existing type instances, much like a &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx"&gt;fictional&lt;/a&gt;&amp;nbsp;&lt;a href="http://stackoverflow.com/questions/619033/does-c-sharp-have-extension-properties"&gt;extension property&lt;/a&gt; could be. This topic is not covered much, and since it has to do with the GC, it is often misunderstood.&lt;/p&gt;
&lt;p&gt;The idea is pretty simple: It is a dictionary that takes an type instance as a key, and a value associated to it. The key is stored as a weak reference, meaning that the data is held as a hard-reference as long as the key lives. When the key is collected by the GC, the hard-link is removed, making the data available for collection if it&amp;rsquo;s not referenced anywhere else.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s how to use it:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;ConditionalWeakTable&amp;lt;object, object&amp;gt; table 
    = new ConditionalWeakTable&amp;lt;object, object&amp;gt;();

var o1 = new object();
var o2 = new object();
var r2 = new WeakReference(o2);

table.Add(o1, o2);

//Release the reference so it's only kept by the table
o2 = null;

GC.Collect(2);
Console.WriteLine("{0}/{1}", r2.IsAlive, table.GetOrCreateValue(o1));

// Release the key instance, hence releasing o2.
o1 = null;

GC.Collect(2);
Console.WriteLine("{0}", r2.IsAlive);

//
// Output:
//
//      True/System.Object
//      False
&lt;/pre&gt;
&lt;p&gt;Implementing this class without having a privileged access to the GC is &lt;em&gt;pretty&lt;/em&gt; tricky. You quickly end up having to perform a weak reference dictionary that you&amp;rsquo;ll need to cleanup by hand and you&amp;rsquo;ll need to handle circular references properly. This can end up messy.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Composing the Memoization with the ConditionalWeakTable&lt;/h2&gt;
&lt;p&gt;Knowing this, it is pretty easy to see that it may be possible to create a version of the &lt;em&gt;AsMemoized()&lt;/em&gt; helper that stores its computation results somewhere else, in a memory-friendly fashion.&lt;/p&gt;
&lt;p&gt;The result of a computation can be associated with the data that was used to create it, and kept alive as long as the first source lives.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s how this can be implemented :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;using Storage = System.Collections.Concurrent.ConcurrentDictionary&amp;lt;object, object&amp;gt;;

public static partial class FuncExtensions
{
    private static ConditionalWeakTable&amp;lt;object, Storage&amp;gt; _weakResults =
        new ConditionalWeakTable&amp;lt;object, Storage&amp;gt;();

    public static Func&amp;lt;TParam, TResult&amp;gt; 
        AsWeakMemoized&amp;lt;TSource, TResult, TParam&amp;gt;(
            this Func&amp;lt;TSource, TParam, TResult&amp;gt; selector,
            TSource source
        )
    {
        return param =&amp;gt;
        {
            // Get the dictionary that associates delegates 
            // to a parameter, on the specified source
            var values = _weakResults.GetOrCreateValue(source);

            object res;

            var key = new { selector, param };

            // Get the result for the combination source/selector/param
            bool cached = values.TryGetValue(key, out res);

            if (!cached)
            {
                res = selector(source, param);

                values[key] = res;
            }

            return (TResult)res;
        };
    }
        
    // Since is not possible to implicitly make a Func&amp;lt;T,U&amp;gt; out
    // of a method group, let's use the source as a function type inference.
    public static TResult ApplyMemoized&amp;lt;TSource, TResult, TParam&amp;gt;(
        this TSource source, Func&amp;lt;TSource, TParam, TResult&amp;gt; selector,
        TParam param
    )
    {
        return selector.AsWeakMemoized(source)(param);
    }
}
&lt;/pre&gt;
&lt;p&gt;And is used like this :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;class Program
{
    static void Main(string[] args)
    {
        var data = new Data(42);
        var wr = new WeakReference(data.DoStuff(42));
        var wr2 = new WeakReference(data.DoStuff(42));

        GC.Collect(2);
        Console.WriteLine(wr.IsAlive);

        data = null;

        GC.Collect(2);
        Console.WriteLine(wr.IsAlive);
    }
}

// An immutable type
public class Data
{
    public Data(int value) { Value = value; }
    ~Data() { Console.WriteLine("~Data({0})", Value); }

    public int Value { get; private set; }
}

public static class DataExtensions
{
    public static Data DoStuff(this Data data, int someValue)
    {
        return data.ApplyMemoized(InternalDoStuff, someValue);
    }

    private static Data InternalDoStuff(Data data, int someValue)
    {
        Console.WriteLine("Computing {0}", someValue);
        return new Data(data.Value + someValue);
    }
}

//
// Output: 
//      Computing 42
//      True
//      False
//      ~Data(84)
//      ~Data(42)
//
&lt;/pre&gt;
&lt;p&gt;The ConditionalWeakDictionary takes the instance to attach the result to, a function to memoize, and will return a new delegate that will cache the results for a combination of the source and a parameter.&lt;/p&gt;
&lt;p&gt;Note that to reduce the verbosity of the code, since it's not possible to use a method group as a delegate, the ApplyMemoized method&amp;nbsp;is used to take advantage of the few places where the delegate type inference is available.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;AsWeakMemoized, the caveats&lt;/h2&gt;
&lt;p&gt;This helper is far from perfect, and it has to do with the implementation of the ConditionalWeakTable implementation.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Referential Transparency&lt;/h3&gt;
&lt;p&gt;The documentation says &lt;em&gt;"Two keys are equal if passing them to the Object.ReferenceEquals method returns true.". &lt;/em&gt;This means that the even though two instances of the same data may be equal in their value, through &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx"&gt;IEquatable&lt;/a&gt; or GetHashCode/Equals, they will be considered as different. This means that through this helper, type instances&amp;nbsp;are not &lt;a href="http://en.wikipedia.org/wiki/Referential_transparency_(computer_science)"&gt;referentially transparent&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;When&amp;nbsp;using AsWeakMemoized, this is an implementation&amp;nbsp;detail that needs to be taken into account. The same computation may be performed twice because the computation will be memoized on a &lt;a href="http://msdn.microsoft.com/en-us/library/bb548891.aspx"&gt;projection&lt;/a&gt; of an immutable instance.&lt;/p&gt;
&lt;p&gt;I mentioned earlier that implementing a ConditionalWeakTable can be tricky, but implementing referential transparency could be a reason to do it. This would allow for the memoizer to&amp;nbsp;compare values instead of references.&lt;/p&gt;
&lt;p&gt;But it would also&amp;nbsp;make memory management a bit more complex,&amp;nbsp;regarding&amp;nbsp;the owner of the computation result. For instance, there is the question of&amp;nbsp;how long a&amp;nbsp;referentially transparent result for a single value should be&amp;nbsp;kept alive, even if the original reference that was used to create the resulting value has been collected.&lt;/p&gt;
&lt;p&gt;You might want to go down that road :)&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Static delegates&lt;/h3&gt;
&lt;p&gt;You'll notice that the memoization is using the delegate as a key for the storage. This means that if the provided delegate&amp;nbsp;changes, either because it is a lambda that creates a closure, or because the delegate is created from an instance method, the memoization will not happen.&lt;/p&gt;
&lt;p&gt;At the very worse, the memoization will do nothing, or maybe simply allocate a few more bytes every time for the storage of the result.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Occasional Duplicate Work&lt;/h3&gt;
&lt;p&gt;Finally, you'll notice that there are no locks in this implementation. This means that the computation for a set of inputs may occasionally&amp;nbsp;be executed multiple times in case of a race condition. While this can be a performance&amp;nbsp;issue on systems that do not have enough CPUs (&amp;lt; 4), on greater multicore CPUs,&amp;nbsp;it is acceptable to have the CPUs occasionally compute the same data even if it is discarded, just for the sake of avoiding acquiring&amp;nbsp;locks.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Final words&lt;/h2&gt;
&lt;p&gt;I personally think that Functional Programming concepts such as Immutability and method purity,&amp;nbsp;along with techniques such as Memoization, are part of the answer to harness the power of multi-core CPUs. CPU &lt;a href="https://en.wikipedia.org/wiki/Scalability"&gt;Scaling out&lt;/a&gt; is not going away, so we'd better make good use of this hardware, using&amp;nbsp;the appropriate development&amp;nbsp;tools.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp;&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/04/22/Immutable-Data-and-Memoization-in-CSharp-Part-2.aspx</link>
      <comments>http://jaylee.org/post/2013/04/22/Immutable-Data-and-Memoization-in-CSharp-Part-2.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=3644700f-605d-4988-90df-999014040498</guid>
      <pubDate>Mon, 22 Apr 2013 21:10:00 -0600</pubDate>
      <category>.NET</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=3644700f-605d-4988-90df-999014040498</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=3644700f-605d-4988-90df-999014040498</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/04/22/Immutable-Data-and-Memoization-in-CSharp-Part-2.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=3644700f-605d-4988-90df-999014040498</wfw:commentRss>
    </item>
    <item>
      <title>Immutable Data and Memoization in C#, Part 1</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: Immutable data and memoization are functional programming concepts that can be applied to C# programming. These patterns have their strengths and weaknesses,&amp;nbsp;discussed a bit&amp;nbsp;in this article.&amp;nbsp;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve grown to not being a great fan a data mutability.&lt;/p&gt;
&lt;p&gt;Data mutability can introduce a lot of side effects in the code, and it can be pretty complex to go back in time to know what a specific state was before the code failed. This gets worse when multiple threads are involved, and that tends to happen a lot more these days, now that even phones have multiple cores.&lt;/p&gt;
&lt;p&gt;Sure, we can use &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee336126.aspx"&gt;IntelliTrace &lt;/a&gt;to ease that kind of debugging, but that&amp;rsquo;s pretty much limited to issues you already know about. That means you&amp;rsquo;re reacting to issues that already happened, you&amp;rsquo;re not proactively preventing those issues from happening.&lt;/p&gt;
&lt;p&gt;So, to address this more reliably, there&amp;rsquo;s the concept of &lt;a href="https://en.wikipedia.org/wiki/Immutable_object"&gt;immutability&lt;/a&gt;. When a set of data is built, it cannot change anymore. This means that you can pass it around, do computation with it, use it any place you want, there&amp;rsquo;s not going to be any subtle concurrency issues because the data changed under your feet.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;Immutability and Performance&lt;/h2&gt;
&lt;p&gt;The thing is, taken as is, immutability is not&amp;nbsp;great friend of performance at first. When a computation is performed, the result is just passed to the next function that needs it, but if there is another function that depends on that same function's output, for the same input, then the computation is performed again.&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s already a solution for this problem, known as &lt;a href="https://en.wikipedia.org/wiki/Memoization"&gt;Memoization&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The basic idea is that, if the input data is immutable, and that the computation has no side effect, then for a given set of inputs, the output will always be the same. This in turn, means that the result can be cached for later reuse. This is called &lt;a href="http://en.wikipedia.org/wiki/Referential_transparency_(computer_science)"&gt;Referential Transparency&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s a simple example of memoization :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static Func&amp;lt;TArg, TResult&amp;gt; 
   AsMemoized&amp;lt;TArg, TResult&amp;gt;(this Func&amp;lt;TArg, TResult&amp;gt; func)
{
    var values = new Dictionary&amp;lt;TArg, TResult&amp;gt;();

    return (v) =&amp;gt;
    {
        TResult value;

        if (!values.TryGetValue(v, out value))
        {
            value = values[v] = func(v);
        }

        return value;
    };
}
    &lt;/pre&gt;
&lt;p&gt;And here a simple use for this, where you know the data won&amp;rsquo;t change :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;static void Main(string[] args)
{
    // Get the JIT out of the way
    GetAssignableTypes(typeof(IDisposable));

    Func&amp;lt;Type, Type[]&amp;gt; getAssignableTypes = GetAssignableTypes;
    getAssignableTypes = getAssignableTypes.AsMemoized();

    for (int i = 0; i &amp;lt; 10; i++)
    {
        var sw1 = Stopwatch.StartNew();
        var r1 = getAssignableTypes(typeof(IDisposable)).Length;
        Console.WriteLine(sw1.Elapsed);
    }
}

public static Type[] GetAssignableTypes(Type source)
{
    var r =
        from asm in AppDomain.CurrentDomain.GetAssemblies()
        from type in asm.GetTypes()
        where type.IsAssignableFrom(source)
        select type;

    return r.ToArray();
}
&lt;/pre&gt;
&lt;p&gt;The first call takes about 90ms on my machine, at the rest about 0.7&amp;micro;s to execute.&lt;/p&gt;
&lt;p&gt;As most of the time, this is tradeoff between memory and CPU. In this case, the result of the computation is store in a dictionary that is capture in the closure created in the AsMemoized method.&lt;/p&gt;
&lt;p&gt;So, as long as the delegate produced by AsMemoized lives, so will the cached data.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Memoization storage and Immutability&lt;/h2&gt;
&lt;p&gt;But there are multiple issues with this pattern of memoization, meaning that the memoized delegate needs to be stored somewhere.&lt;/p&gt;
&lt;p&gt;The first issue is that the memoized delegate can be stored along with an instance that has a greater lifetime. This can work if the overall memoized dataset is not too important, because with a na&amp;iuml;ve implementation as the one above, the data will not be discarded as long as the outer instance lives. The memoization can be reset, by re-creating the delegate, but it is&amp;nbsp;very coarse.&lt;/p&gt;
&lt;p&gt;The second one is about placing the memoized delegate along with the data that was used to create it. The memoized content will live as long as the data is alive, but there is a clear separation of concerns issue. Every time there is a new operation that needs to be performed on this data, then a new delegate has to be created to take care of this.&lt;/p&gt;
&lt;p&gt;And finally, if there is a need for composite computation, which takes two or more instances, at this point, storing the delegate can be a memory-management challenge.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Next time&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://www.jaylee.org/post/2013/04/22/Immutable-Data-and-Memoization-in-CSharp-Part-2.aspx"&gt;Next time&lt;/a&gt;, we'll see how memoization can be a little more friendly with the memory.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/04/18/Memoization-and-Immutable-data-in-CSharp-Part-1.aspx</link>
      <comments>http://jaylee.org/post/2013/04/18/Memoization-and-Immutable-data-in-CSharp-Part-1.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=c0484faa-93d5-46df-97a1-e0116afe3382</guid>
      <pubDate>Thu, 18 Apr 2013 20:49:00 -0600</pubDate>
      <category>.NET</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=c0484faa-93d5-46df-97a1-e0116afe3382</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=c0484faa-93d5-46df-97a1-e0116afe3382</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/04/18/Memoization-and-Immutable-data-in-CSharp-Part-1.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=c0484faa-93d5-46df-97a1-e0116afe3382</wfw:commentRss>
    </item>
    <item>
      <title>Cancellation with Async F#, C# and the Reactive Extensions</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: C# 5.0 async/await&amp;nbsp;does not include the implicit support for cancellation, and needs to pass CancellationToken instances to every async method. F# and the Reactive Extensions offer solutions to this problem, with both implicit and explicit support for cancellation.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;My development style has slowly shifted to a more functional approach, during the past year. I&amp;rsquo;ve been peeking a F# for a while and that shift to a more functional mindset&amp;nbsp;in C# lends me toward understanding a lot better the concepts behind core features of F#, and more specifically the async &amp;ldquo;support&amp;rdquo; in F#.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s known that F# inspired a lot the implementation of C# async, but having looked at the way it&amp;rsquo;s been implemented in F# gives me some more points against the &amp;ldquo;unfinished&amp;rdquo; implementation in C#.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Recently, now that people are effectively using async, in real-world scenarios, problems are starting to bubble up, and some to &lt;a href="https://twitter.com/josefajardo/status/303998917027192832"&gt;giggle&lt;/a&gt;. &lt;a href="http://www.jaylee.org/post/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.aspx"&gt;Async void, async void lambdas&lt;/a&gt;, the fact that continuations run mostly on the UI thread when not taken care of properly, &lt;a href="http://www.jaylee.org/post/2012/09/29/C-Async-Tips-and-Tricks-Part-3-Tasks-and-the-Synchronization-Context.aspx"&gt;obscure exception handling scenarios&lt;/a&gt;, &lt;a href="http://www.jaylee.org/post/2012/06/18/CSharp-5-0-Async-Tips-and-Tricks-Part-1.aspx"&gt;the &amp;ldquo;magic&amp;rdquo; relation to the SynchronizationContext&lt;/a&gt;, that it does not address parallelism, and one that&amp;rsquo;s been pretty&amp;nbsp;low-key, &lt;strong&gt;cancellation&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Cancellation is pretty important, particularly, when the operations can take a pretty long time. If the user awaits an async result, he may have the right to cancel the operation, either because it took too long, or because the rest of the processing is not needed, as&amp;nbsp;the user&amp;nbsp;has gone away. This avoids wasting precious CPU cycles, and sometimes network or I/O related&amp;nbsp;resources for computations for which the result will not be used.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Cancelling a C# async method&lt;/h2&gt;
&lt;p&gt;Now, consider the following code sample, that tries to cancel the execution of an async method:&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static void Run()
{
    var cts = new CancellationTokenSource();
    Task.Run(async () =&amp;gt; await Test(), cts.Token);
    Console.ReadLine();
    cts.Cancel();
    Console.WriteLine("Cancel...");
    Console.ReadLine();
}

private static async Task Test()
{
    while (true)
    {
        await Task.Delay(1000);
        Console.WriteLine("Test...");
    }
}
&lt;/pre&gt;
&lt;p&gt;Which produces the following output :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;Test...
Test...
Test...

Cancel...
Test...
Test...
Test...
Test...
&lt;/pre&gt;
&lt;p&gt;The problem here is pretty simple: the cancellation token only cancels the task created by Task.Run(). This can be problematic, particularly if the sub-tasks are computationally intensive, or are making external calls (e.g. an http web request) that effectively need to be cancelled.&lt;/p&gt;
&lt;p&gt;With&amp;nbsp;the TPL, the notion of cancellation is present through the concept of &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.aspx"&gt;CancellationToken&lt;/a&gt;. A cancellation token is basically a glorified thread-safe boolean value that tells that it&amp;rsquo;s creator, a &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource.aspx"&gt;CancellationTokenSource&lt;/a&gt;, has been cancelled.&lt;/p&gt;
&lt;p&gt;So, there are two things to do to support cancellation in an async method.&lt;/p&gt;
&lt;p&gt;First, by passing a CancellationToken explicitly and poll the token frequently&amp;nbsp;:&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static void Run()
{
    var cts = new CancellationTokenSource();
    Task.Run(async () =&amp;gt; await Test(cts.Token), cts.Token);
    Console.ReadLine();
    cts.Cancel();
    Console.WriteLine("Cancel...");
    Console.ReadLine();
}

private static async Task Test(CancellationToken token)
{
    while (true)
    {
        await Task.Delay(1000);
        Console.WriteLine("Test...");

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
    Console.WriteLine("Test cancelled");
}
&lt;/pre&gt;
&lt;p&gt;Second, via a delegate passed through &lt;a href="http://msdn.microsoft.com/en-us/library/dd321635.aspx"&gt;CancellationToken.Register&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static void Run()
{
    var cts = new CancellationTokenSource();
    Task.Run(async () =&amp;gt; await Test(cts.Token), cts.Token);
    Console.ReadLine();
    cts.Cancel();
    Console.WriteLine("Cancel...");
    Console.ReadLine();
}

private static async Task Test(CancellationToken token)
{
    var wr = HttpWebRequest.Create("http://1.2.3.4");

    token.Register(() =&amp;gt; { 
        Console.WriteLine("Query cancelled");
        wr.Abort(); 
    });

    var r = await Task&amp;lt;WebResponse&amp;gt;.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);

    if (token.IsCancellationRequested)
    {
        return;
    }

    Console.WriteLine("Got a result");
}&lt;/pre&gt;
&lt;p&gt;There are multiple problems with this approach, one being that the cancellation token&amp;nbsp;parameter needs to appear explicitly in every single method of the call tree. If you have multiple layers of code and abstractions, cancellation becomes pretty much prominent.&lt;/p&gt;
&lt;p&gt;Second is, to be thorough, to check the cancellation token as often as possible to avoid continuing doing work if it&amp;rsquo;s not necessary, even if you've detected that the task has been cancelled.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Cancelling an F# async function&lt;/h2&gt;
&lt;p&gt;With F#, &lt;a href="http://msdn.microsoft.com/en-us/library/dd233250.aspx"&gt;async&lt;/a&gt; is actually a &amp;ldquo;side-effect&amp;rdquo; of the more powerful feature called the &lt;a href="http://msdn.microsoft.com/en-us/library/dd233182.aspx"&gt;Computation Expressions&lt;/a&gt;. Naively, I see this a super-feature that allows the creation of some of the syntactic sugar based-features of C#, async and the iterators.&lt;/p&gt;
&lt;p&gt;Async support takes the form of an &lt;a href="http://msdn.microsoft.com/en-us/library/dd233250.aspx"&gt;Async type&lt;/a&gt;, that allows the creation of an &amp;ldquo;async&amp;rdquo; computation expression that, in turn, allows for the manipulation of Async&amp;lt;T&amp;gt; returning expressions. If this sounds familiar, you&amp;rsquo;re spot-on, this is roughly the same as Task&amp;lt;T&amp;gt; and C# async/await.&lt;/p&gt;
&lt;p&gt;Now, the interesting thing about these Async&amp;lt;T&amp;gt; expressions is that when created, Async&amp;lt;T&amp;gt; functions respect the cancellation token used when starting the async expression :&lt;/p&gt;
&lt;pre class="brush: text"&gt;open System
open System.Threading
let main argv = 

    let myAsync = 
        async {
            while true do 
                do! Async.Sleep(1000)
                Console.WriteLine(DateTime.Now)
        }

    let tokenSource1 = new System.Threading.CancellationTokenSource()
    let val1 = Async.Start(myAsync, cancellationToken=tokenSource1.Token)    
    Console.ReadLine() |&amp;gt; ignore
    tokenSource1.Cancel()
    Console.ReadLine() |&amp;gt; ignore
    0&lt;/pre&gt;
&lt;p&gt;When cancelled, the async expression stops processing its content, without any explicit support of the token.&lt;/p&gt;
&lt;p&gt;But the most interesting part in this is that this token flows through to the other async expressions !&lt;/p&gt;
&lt;p&gt;To better demonstrate this, there is the ability to register a function that will be called when the async expression is called :&lt;/p&gt;
&lt;pre class="brush: text"&gt;let main argv = 

    let r2 = 
        async {
            use! c = Async.OnCancel(fun () -&amp;gt; Console.WriteLine("Cancelled 1"))

            // In case there is a non async computation that needs 
            // to check on cancellation
            let! token = Async.CancellationToken
            
            while true do 
                do! Async.Sleep(1000)
                Console.WriteLine(DateTime.Now)

            return 42
        }

    let r = 
        async {
            use! c = Async.OnCancel(fun () -&amp;gt; Console.WriteLine("Cancelled 2"))

            let! test = r2

            while true do 
                do! Async.Sleep(100)

            return 42
        }

    let tokenSource1 = new System.Threading.CancellationTokenSource()
    let res3 = Async.StartAsTask(r, cancellationToken=tokenSource1.Token)    
    Console.ReadLine() |&amp;gt; ignore
    tokenSource1.Cancel()
    Console.ReadLine() |&amp;gt; ignore
    0&lt;/pre&gt;
&lt;p&gt;This way, there is no explicit need for passing around a cancellation token, and if it is needed, then it can be used explicitly. There is also the ability to asynchronously get the ambient &lt;a href="http://msdn.microsoft.com/en-us/library/ee353544.aspx"&gt;CancellationToken&lt;/a&gt;&amp;nbsp;(which is also async !), in case there is a CPU bound computation that needs to be cancelled. Or you can just call any ! (bang) operator that will automatically check on the cancellation.&lt;/p&gt;
&lt;p&gt;Pretty powerful !&lt;/p&gt;
&lt;h2&gt;Cancelling an Rx query&lt;/h2&gt;
&lt;p&gt;On the same topic of cancellation, the &lt;a href="http://msdn.microsoft.com/en-us/data/gg577609"&gt;Reactive Extensions&lt;/a&gt; also have the notion of cancellation embedded into the flow.&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static void Run()
{
    var s = Observable.Create(o =&amp;gt;
        {
            var wr = HttpWebRequest.Create("http://1.2.3.4");

            var subscriptions = new CompositeDisposable();

            subscriptions.Add(Disposable.Create(() =&amp;gt; wr.Abort()));

            var s = Observable
                .FromAsyncPattern(wr.BeginGetResponse, wr.EndGetResponse)()
                .Subscribe(o);

            subscriptions.Add(s);

            return subscriptions;
        }
    )
    .Subscribe(_ =&amp;gt; Console.WriteLine("Got result"));

    Console.ReadLine();
    s.Dispose();
    Console.ReadLine();
}
&lt;/pre&gt;
&lt;p&gt;Every observable can be subscribed to, and returns a disposable instance. Whenever the final subscription gets disposed, the whole query gets disposed as well, along with the ability to intercept that disposition with the Observable.Create operator.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Final words&amp;hellip;&lt;/h2&gt;
&lt;p&gt;Cancellation is an important topic that has been &amp;ldquo;forgotten&amp;rdquo; in C# async. This is a very important topic, and this one adds up to all the others about the implementation in C# 5.0, for which I hope this will get fixed in a future release in the language.&lt;/p&gt;
&lt;p&gt;For the moment, both Rx and F# approach async in a more thorough manner, and moreover, attack head-on the concurrency side of asynchrony which is ignored by C# 5.0...&lt;/p&gt;
&lt;p&gt;If you're interested in a more detailed comparison of F# and C# on the subject,&amp;nbsp;read &lt;a href="http://tomasp.net/blog/csharp-fsharp-async-intro.aspx"&gt;Tomas Petricek blog post series&lt;/a&gt;.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/04/16/Cancellation-with-Async-Fsharp-Csharp-and-the-Reactive-Extensions.aspx</link>
      <comments>http://jaylee.org/post/2013/04/16/Cancellation-with-Async-Fsharp-Csharp-and-the-Reactive-Extensions.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=6231ab83-5957-4666-848c-9bb79ff548cb</guid>
      <pubDate>Tue, 16 Apr 2013 20:25:00 -0600</pubDate>
      <category>.NET</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=6231ab83-5957-4666-848c-9bb79ff548cb</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=6231ab83-5957-4666-848c-9bb79ff548cb</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/04/16/Cancellation-with-Async-Fsharp-Csharp-and-the-Reactive-Extensions.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=6231ab83-5957-4666-848c-9bb79ff548cb</wfw:commentRss>
    </item>
    <item>
      <title>Building in Parallel Across Multiple Build Agents in TFS2012 for Metro Apps</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: Using an upgraded (and fixed) &lt;/em&gt;&lt;a href="http://blogs.msdn.com/b/jimlamb/archive/2010/09/14/parallelized-builds-with-tfs2010.aspx"&gt;&lt;em&gt;Parallel Build Process Template&lt;/em&gt;&lt;/a&gt;&lt;em&gt; 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.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Download the Parallel Build Process Template for TFS2012 &lt;a href="http://jaylee.org/files/ParallelTemplate.11.1.zip"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;CI is a wonderful feature, especially when associated with &lt;a href="http://msdn.microsoft.com/en-us/library/dd787631.aspx"&gt;Gated Checkins&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;You&amp;rsquo;re certain that what&amp;rsquo;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&amp;rsquo;s a minimum.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Build time matters&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;This means that the longer your build gets, the longer a developer might wait for its task completion because of a long build queue,&amp;nbsp;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.&lt;/p&gt;
&lt;p&gt;Below 4 minutes of build time, this stays in the acceptable range where the developer&amp;rsquo;s task context may not be lost if the build fails.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;The case of Metro Apps&lt;/h2&gt;
&lt;p&gt;Metro apps are a bit tricky in this regard, because when a .NET based app needs a native dependency, such as &lt;a href="http://visualstudiogallery.msdn.microsoft.com/bb764f67-6b2c-4e14-b2d3-17477ae1eaca"&gt;Bing Maps SDK&lt;/a&gt;, then it is not possible to use the Any CPU configuration anymore.&lt;/p&gt;
&lt;p&gt;In such case, building the app requires the target the three Metro Apps supported platforms: ARM, x86, x64.&lt;/p&gt;
&lt;p&gt;The msbuild configuration for metro apps&amp;nbsp;enforces that all projects for a single platform be compiled under the same platform, meaning that every assembly must be build three times to produce a complete app submission package.&lt;/p&gt;
&lt;p&gt;If your build takes 4 minutes for one platform, then multiply it by three (or more)&amp;nbsp;for all platforms. This is where the CI build time gets in the way of development efficiency.&lt;/p&gt;
&lt;p&gt;And if you&amp;rsquo;re multi-targeting to include Windows Phone apps, and desktop apps that share code with metro apps, Build Time can get out of hand very quickly. And I'm not even&amp;nbsp;mentioning obfuscation...&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Building in Parallel&lt;/h2&gt;
&lt;p&gt;I&amp;rsquo;m a fan of msbuild projects authoring (over Workflow authoring) but in this case, msbuild does not cut it. This will probably please my&amp;nbsp;TFS MVP&amp;nbsp;friend &lt;a href="http://blogs.codes-sources.com/etienne/default.aspx"&gt;Etienne Margraff&lt;/a&gt;, which gives a lot of love to customizing its workflows.&lt;/p&gt;
&lt;p&gt;When building using msbuild, parallelization can occur inside a single solution, for a single Configuration/Platform combination. While this improve the build time a bit, this does not work at all for multiple combinations.&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s also the trick that the guys over a the &lt;a href="http://msbuildextensionpack.codeplex.com/"&gt;MSBuild Extension Pack&lt;/a&gt; that enables the execution of multiple tasks inside of a single MSBuild project file to &lt;a href="http://mikefourie.wordpress.com/2012/02/29/executing-msbuild-targets-in-parallel-part-1/"&gt;run&lt;/a&gt; in &lt;a href="http://mikefourie.wordpress.com/2012/04/18/executing-msbuild-targets-in-parallel-part-2/"&gt;parallel&lt;/a&gt;. The problem with this is that the same source tree is used for all builds at the same time, which can cause trouble over shared files or resources. You have to make sure that all projects include the platform in their respective outputs, but even with that, you can&amp;rsquo;t be sure that a race condition might not happen at any time.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Using the Parallel Build Process Template&lt;/h2&gt;
&lt;p&gt;A few years back, a &lt;a href="http://blogs.msdn.com/b/jimlamb/archive/2010/09/14/parallelized-builds-with-tfs2010.aspx"&gt;Jim Lamb posted a custom Build Process Template&lt;/a&gt; that allows to build multiple configurations in parallel. The beauty of this template is that it allows for each configuration to run on a separate build agent !&lt;/p&gt;
&lt;p&gt;This means that the build can be split on multiple machines, running each on their own copy of the source tree, avoiding race conditions over shared resources from the source tree.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve migrated a few projects over to this updated template and the results are very interesting. &lt;strong&gt;A build that would take 11 minutes to run would fall down to 3.5 minutes when ran over three build agents on the same machine.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One thing though, the original template is built for TFS2010, so I had to port it over to TFS2012 using &lt;a href="http://blogs.msdn.com/b/jpricket/archive/2012/07/17/tfs-2012-cleaning-up-workflow-xaml-files-aka-removing-versioned-namespaces.aspx"&gt;this cleanup tool from Jason Prickett&lt;/a&gt;. If you don&amp;rsquo;t want to migrate it by yourself, download the file at the top of the post.&lt;/p&gt;
&lt;p&gt;I also had to modify the original error handling, because if one of the configuration build failed, the overall build would not fail. In the context of a gated checkin, this can be problematic&amp;hellip;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Getting a bit farther&lt;/h2&gt;
&lt;p&gt;The interesting thing with this parallel build template is that it can be used to parallelize validation or non-output generating tasks. For instance, creating a zip file of the source tree, validating some portions of the xaml for best practices, running some non-interactive unit tests&amp;hellip; and so on.&lt;/p&gt;
&lt;p&gt;This relies on scaling out, instead of scaling up, which is more than welcome, particularly in virtualized environments.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/03/30/Building-in-Parallel-Across-Multiple-Build-Agents-with-TFS-2012-with-Gated-Checkin.aspx</link>
      <comments>http://jaylee.org/post/2013/03/30/Building-in-Parallel-Across-Multiple-Build-Agents-with-TFS-2012-with-Gated-Checkin.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=34e21de5-a15a-407f-a59f-70c40e7edbad</guid>
      <pubDate>Sat, 30 Mar 2013 12:50:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <category>Windows Phone Dev</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=34e21de5-a15a-407f-a59f-70c40e7edbad</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=34e21de5-a15a-407f-a59f-70c40e7edbad</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/03/30/Building-in-Parallel-Across-Multiple-Build-Agents-with-TFS-2012-with-Gated-Checkin.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=34e21de5-a15a-407f-a59f-70c40e7edbad</wfw:commentRss>
    </item>
    <item>
      <title>[VS2012] Temporarily disable the C# static code analysis for a whole VS instance</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: It is possible to disable the Static Analysis phase in VS2012 projects by setting the &lt;strong&gt;DevDivCodeAnalysisRunType&lt;/strong&gt; environment variable to &amp;ldquo;&lt;strong&gt;Disabled&lt;/strong&gt;&amp;rdquo;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This will be a quick post, but which might save you a lot of time if you rely heavily on &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441471(v=VS.85).aspx"&gt;Code Analysis (FxCop)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;FxCop is definitely not known for its analysis speed, and when ran in every build, this takes a lot of time. I usually work on projects where FxCop is only enabled in the Release Configuration, which helps during development in Debug configuration.&lt;/p&gt;
&lt;p&gt;But if you&amp;rsquo;re bound to run in Release configuration, such as when profiling the app, or any other task that requires to build in that configuration, then having FxCop running every single time can be time consuming.&lt;/p&gt;
&lt;p&gt;To avoid this, there are multiple choices :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use find and replace to change &lt;strong&gt;&amp;lt;RunCodeAnalysis&amp;gt;true&amp;lt;/RunCodeAnalysis&amp;gt;&lt;/strong&gt; to &lt;strong&gt;&amp;lt;RunCodeAnalysis&amp;gt;false&amp;lt;/RunCodeAnalysis&amp;gt;&lt;/strong&gt;, but then you have to remember to not check that into your source control (even if the &lt;strong&gt;Perform Code Analysis&lt;/strong&gt; setting is set to &lt;strong&gt;Always&lt;/strong&gt; in&amp;nbsp;your CI Build definition),&lt;/li&gt;
&lt;li&gt;Create an alternate configuration similar to &lt;strong&gt;Release&lt;/strong&gt; that does not have the Static Code Analysis enabled, but changing configurations in VS2012&amp;nbsp;can take time (even with the Update 2) and you&amp;rsquo;ll have to maintain that configuration with the others,&lt;/li&gt;
&lt;li&gt;Or you can use a little trick to disable the static code analysis for a whole Visual Studio instance.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;That trick is a bit hidden, but here&amp;rsquo;s how you can do this :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Open a &lt;strong&gt;Developer Command Prompt for VS2012&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;type &lt;strong&gt;set&lt;/strong&gt; &lt;strong&gt;DevDivCodeAnalysisRunType=Disabled&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;type &lt;strong&gt;devenv&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Build your solution and you won&amp;rsquo;t have the static analysis running, without any modification to your solutions&amp;rsquo; configuration or projects. Easy.&lt;/p&gt;
&lt;p&gt;That said, remember that this is not documented and &lt;strong&gt;might change at any point in the future&lt;/strong&gt; so don't rely on it too much.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/03/30/VS2012-Temporarily-disable-the-C-static-code-analysis-for-a-whole-VS-instance.aspx</link>
      <comments>http://jaylee.org/post/2013/03/30/VS2012-Temporarily-disable-the-C-static-code-analysis-for-a-whole-VS-instance.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=a625013b-0f10-4d9f-9564-733e9b915d5e</guid>
      <pubDate>Sat, 30 Mar 2013 11:52:00 -0600</pubDate>
      <category>.NET</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=a625013b-0f10-4d9f-9564-733e9b915d5e</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=a625013b-0f10-4d9f-9564-733e9b915d5e</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/03/30/VS2012-Temporarily-disable-the-C-static-code-analysis-for-a-whole-VS-instance.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=a625013b-0f10-4d9f-9564-733e9b915d5e</wfw:commentRss>
    </item>
    <item>
      <title>Writing a Xaml attached property in C++/CX to resize Images, with a Performance twist</title>
      <description>&lt;p&gt;&lt;em&gt;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.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;There is, after all, some marshaling involved when communicating from C# to native code, particularly with events.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;The ImageDecodeSizeBehavior&lt;/h2&gt;
&lt;p&gt;WinRT&amp;rsquo;s &lt;a href="http://msdn.microsoft.com/en-us/library/ms619224.aspx"&gt;BitmapImage&lt;/a&gt; class supports, as does WPF and Silverlight, the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.decodepixelwidth.aspx"&gt;DecodePixelWidth&lt;/a&gt;&amp;nbsp;and DecodePixelHeight properties.&lt;/p&gt;
&lt;p&gt;These&amp;nbsp;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 &lt;strong&gt;very&lt;/strong&gt; quickly.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;So in C#, the following attached property can be written pretty easily :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public static class ImageDecodeSizeBehavior
{
    public static void SetSource(Image image, string value)
    {
        image.SetValue(SourceProperty, value);
    }

    public static string GetSource(Image image)
    {
        return (string)image.GetValue(SourceProperty);
    }

    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            "Source",
            typeof(string), 
            typeof(ImageDecodeSizeBehavior), 
            new PropertyMetadata(null, (s, e) =&amp;gt; OnSourceChanged(s, e))
        );

    private static void OnSourceChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
    {
        var image = (Image)s;

	    image.SetValue(SourceProperty, e.NewValue);

	    image.SizeChanged += (_, __) =&amp;gt; RefreshBitmap(image);

	    RefreshBitmap(image);
    }

    private static void RefreshBitmap(Image image)
    {
	    var source = (String)image.GetValue(SourceProperty);

	    if(source != null)
	    {
		    var uri = new Uri(source);
		    var bitmap = new BitmapImage(uri);

		    bitmap.DecodePixelWidth = (int)image.Width;
		    bitmap.DecodePixelHeight = (int)image.Height;

		    image.Source = bitmap;
	    }
    }
}
&lt;/pre&gt;
&lt;p&gt;&lt;span&gt;The idea here is to use the current image control size as the target surface size, do be gentle with the memory. The downside is that if images need to be zoomed in, then they're going to be pixelated, unless the image is re-created.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In this sample, the hook on SizeChanged is more of a speed test, because one would not want to re-create the image every time the size changes, particularly if it changes too much (though the Rx Throttle operator may help).&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s used that way :&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;Image local:ImageDecodeSizeBehavior.Source="{Binding}" Width="50" Height="50" /&amp;gt;&lt;/pre&gt;
&lt;pre class="brush: xml"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;h2&gt;The same, in C++/CX&lt;/h2&gt;
&lt;p&gt;With C++/CX, the code is looking very much like its C# counter part :&lt;/p&gt;
&lt;pre class="brush: cpp"&gt;using namespace Platform;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media::Imaging;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Metadata;

public ref class ImageDecodeSizeBehavior sealed : DependencyObject
{
public:
	ImageDecodeSizeBehavior();

	static property DependencyProperty^ SourceProperty { 
		DependencyProperty^ get() { return _sourceProperty; }
	}

	static String^ ImageDecodeSizeBehavior::GetSource(Image^ image) {
		return (String^)image-&amp;gt;GetValue(SourceProperty);
	}

	static void ImageDecodeSizeBehavior::SetSource(Image^ image, String^ source) {
		image-&amp;gt;SetValue(SourceProperty, source);
	}

private:
	~ImageDecodeSizeBehavior();

	static DependencyProperty^ _sourceProperty;

	static void RefreshBitmap(Image^ image, String^ value);
	static void OnSourceChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e);
};
&lt;/pre&gt;
&lt;p&gt;And the cpp file:&lt;/p&gt;
&lt;pre class="brush: cpp"&gt;using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Documents;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Imaging;

DependencyProperty^ ImageDecodeSizeBehavior::_sourceProperty = 
	DependencyProperty::RegisterAttached(
		"Source", 
		TypeName(String::typeid), 
		TypeName(ImageDecodeSizeBehavior::typeid), 
		ref new PropertyMetadata(
			nullptr, 
			ref new PropertyChangedCallback(OnSourceChanged)
		)
	);

void ImageDecodeSizeBehavior::OnSourceChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
	auto image = (Image^)d;
	auto value = (String^)e-&amp;gt;NewValue;

	image-&amp;gt;SetValue(SourceProperty, value);

	auto sizeChanged = [=](Object^ sender, SizeChangedEventArgs^){
			RefreshBitmap(image, value);
	};

	image-&amp;gt;SizeChanged += ref new SizeChangedEventHandler(sizeChanged);

	RefreshBitmap(image, value);
}


void ImageDecodeSizeBehavior::RefreshBitmap(Image^ image, String^ source)
{
	if(source == nullptr)
	{
		source = (String^)image-&amp;gt;GetValue(SourceProperty);
	}

	if(source != nullptr)
	{
		auto uri = ref new Uri(source);
		auto bitmap = ref new BitmapImage(uri);

		bitmap-&amp;gt;DecodePixelWidth = (int)image-&amp;gt;Width;
		bitmap-&amp;gt;DecodePixelHeight = (int)image-&amp;gt;Height;

		image-&amp;gt;Source = bitmap;
	}
}&lt;/pre&gt;
&lt;p&gt;Except that it&amp;rsquo;s a lot more verbose. Particularly the lambda syntax that uses all the available braces on the keyboard.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Performance&lt;/h2&gt;
&lt;p&gt;How do the two compare, in terms of performance ? Testing this in a real control is a bit complex, because of the performance issue &lt;a href="http://jaylee.org/post/2013/02/02/On-the-Performance-of-WinRTXaml-Template-Expansion.aspx"&gt;I outlined in this post&lt;/a&gt;, but also because the measured time varies a lot, of about +/- 2%. This margin of error is not small enough to show the actual improvements.&lt;/p&gt;
&lt;p&gt;Still, it is possible to measure in a more isolated code :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;var w = Stopwatch.StartNew();
for (int i = 0; i &amp;lt; 1000; i++)
{
   var b = new Image();
   ImageDecodeSizeBehavior.SetSource(b, "http://google.com/images/srpr/logo3w.png");
}
var elapsed = w.Elapsed;
&lt;/pre&gt;
&lt;p&gt;Which shows that, on a Surface RT, attaching to 1000 images takes 722ms in C#, and 505ms in C++/CX, which is about a 30% faster.&lt;/p&gt;
&lt;p&gt;Now, the reason for this difference is the event registration.&lt;/p&gt;
&lt;p&gt;Removing both event registrations sets the bar to 474ms for C++/CX and 493ms for C#, which &lt;em&gt;almost&lt;/em&gt; accounts for all the complexity added by the hidden &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.windowsruntime.eventregistrationtoken.aspx"&gt;EventRegistrationToken &lt;/a&gt;and &lt;a href="http://msdn.microsoft.com/en-us/library/hh138484.aspx"&gt;WindowsRuntimeMarshal.AddEventHandler &lt;/a&gt;magic added by the C# compiler.&lt;/p&gt;
&lt;p&gt;The simple&amp;nbsp;+= operator added in C# is expanded to something like this, in IL :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;WindowsRuntimeMarshal.AddEventHandler(
   new Func(image.add_SizeChanged), 
   new Action(image.remove_SizeChanged), 
   delegate(object _, SizeChangedEventArgs __) {
      ImageDecodeSizeBehavior.RefreshBitmap(image);
   }
);&lt;/pre&gt;
&lt;p&gt;Which is a bit of a change from a simple delegate&amp;nbsp;registration. I'm guessing that there is a lot of work related to reference tracking and marshalling, under the hood, which may account for the loss of performance.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;It is worth the investment ?&lt;/h2&gt;
&lt;p&gt;We&amp;rsquo;re talking about quite small amounts of time, yet we&amp;rsquo;ve got 16.6ms to perform operations on the UI thread, and keep the 60fps rate to preserve smooth animations.&amp;nbsp;So, 0.7ms may count in the balance.&lt;/p&gt;
&lt;p&gt;C++/CX requires a bit more maintenance than its C# counterpart, which may add to the development cost. It also forces the creation of packages for all the available platforms, as it requires the creation of a native WinMD component.&lt;/p&gt;
&lt;p&gt;I, for one, tend to favor maintainability over performance, unless it is in a very critical path.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/02/04/Writing-an-Xaml-attached-property-in-CppCX-to-resize-Images-with-a-Perf-twist.aspx</link>
      <comments>http://jaylee.org/post/2013/02/04/Writing-an-Xaml-attached-property-in-CppCX-to-resize-Images-with-a-Perf-twist.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=b3401df4-6b0b-4e54-a078-f95eb13c9ab5</guid>
      <pubDate>Mon, 04 Feb 2013 21:41:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=b3401df4-6b0b-4e54-a078-f95eb13c9ab5</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=b3401df4-6b0b-4e54-a078-f95eb13c9ab5</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/02/04/Writing-an-Xaml-attached-property-in-CppCX-to-resize-Images-with-a-Perf-twist.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=b3401df4-6b0b-4e54-a078-f95eb13c9ab5</wfw:commentRss>
    </item>
    <item>
      <title>On the Performance of WinRT/Xaml Template Expansion</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: Expanding data-bound item templates in Xaml/WinRT in Windows 8&amp;nbsp;is about a hundred times&amp;nbsp;slower than with Xaml/WPF. This article details how this was measured and a possible explanation.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In Windows 8, Microsoft has a introduced a whole new Xaml stack, codenamed Jupiter, completely re-written to be native only.&lt;/p&gt;
&lt;p&gt;This allows the creation of Xaml controls using C++ as well as C#.&lt;/p&gt;
&lt;p&gt;I will not discuss the philosophical&amp;nbsp;choice of ditching managed WPF in favor of a native rewrite, but make a simple comparison of the performance between the two.&lt;/p&gt;
&lt;h2&gt;&amp;nbsp;&lt;/h2&gt;
&lt;h2&gt;Template Expansion Performance&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;To isolate this, I created a simple UI: &amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;GridView x:Name="testGrid"&amp;gt;
    &amp;lt;GridView.ItemsPanel&amp;gt;
        &amp;lt;ItemsPanelTemplate&amp;gt;
            &amp;lt;VariableSizedWrapGrid /&amp;gt;
        &amp;lt;/ItemsPanelTemplate&amp;gt;
    &amp;lt;/GridView.ItemsPanel&amp;gt;
    &amp;lt;GridView.ItemTemplate&amp;gt;
        &amp;lt;DataTemplate&amp;gt;
            &amp;lt;TextBlock Text="{Binding}" Foreground="Red" /&amp;gt;
        &amp;lt;/DataTemplate&amp;gt;
    &amp;lt;/GridView.ItemTemplate&amp;gt;
&amp;lt;/GridView&amp;gt;&lt;/pre&gt;
&lt;p&gt;Initialized with the following code in a button click :&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre class="brush: c-sharp"&gt;testGrid.ItemsSource = Enumerable.Range(1, 100);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;On a Surface RT tablet, &lt;strong&gt;the time during which the UI was not responding was about 2.1 seconds&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Looking a the profiler revealed that a lot of time was spent in this function :&lt;/p&gt;
&lt;pre&gt;?MeasureOverride@FrameworkElementGenerated@DirectUI@@UAAJUSize@Foundation@Windows@@PAU345@@Z&lt;/pre&gt;
&lt;p&gt;Measuring is expected to take some time to execute, but it was very odd that it was that much.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Measuring between WPF and WinRT&lt;/h2&gt;
&lt;p&gt;As an experiment, I tried to create approximately same layout in WPF, and test the rendering performance on my PC.&lt;/p&gt;
&lt;p&gt;To measure more precisely, I created an override of both the GridView and the ListBox controls so that the call to Measure could be profiled, that way :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;protected override Size MeasureOverride(Size availableSize)
{
   var w = Stopwatch.StartNew();
   try 
   {             
      return base.MeasureOverride(availableSize); 
   }
   finally        
   {                 
      MeasureTime = w.Elapsed;    
      Debug.WriteLine("Measure " + w.Elapsed);         
   }       
}&lt;/pre&gt;
&lt;p&gt;It turns out that the initial measure duration for 500 element is quite different: &lt;strong&gt;WPF measures for 15ms, WinRT does in 1500ms !&lt;/strong&gt; And it appears visually, because the UI is not responding a long time in WinRT, where it does not in WPF. Subsequent measures are roughly the same for both platforms.&lt;/p&gt;
&lt;p&gt;Interestingly, while the VS2012 profiler does not show stack traces below the manaded/native boundary, the concurrency visualizer does. A stacktrace element that comes back &lt;strong&gt;very&lt;/strong&gt; often is the following :&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;windows.ui.xaml.dll!XamlWriter::WriteNode+0x53c&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;Which seems to point in the direction of the lack of template parsing result caching&amp;hellip;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;What then ?&lt;/h2&gt;
&lt;p&gt;That&amp;rsquo;s the problem. Not that much, apart from try to&amp;nbsp;not realize too many collection&amp;nbsp;items in WinRT. (and guessing that for the next update of WinRT that may address this)&lt;/p&gt;
&lt;p&gt;Another solution can be to Databind an ObservableCollection and add items slowly to yield the template creation on the UI Thread... But this requires some plumbing code to avoid race conditions and sorting issues.&lt;/p&gt;
&lt;p&gt;This makes UI virtualization very important with Virtualizing Panels, to reuse as many control instances as possible. This also implies that your visual design should not display too many items at once on the screen, with small logical dimensions.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/02/02/On-the-Performance-of-WinRTXaml-Template-Expansion.aspx</link>
      <comments>http://jaylee.org/post/2013/02/02/On-the-Performance-of-WinRTXaml-Template-Expansion.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=5fbf0416-0229-4f52-b9ea-17cf55354509</guid>
      <pubDate>Sat, 02 Feb 2013 15:11:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=5fbf0416-0229-4f52-b9ea-17cf55354509</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=5fbf0416-0229-4f52-b9ea-17cf55354509</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/02/02/On-the-Performance-of-WinRTXaml-Template-Expansion.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=5fbf0416-0229-4f52-b9ea-17cf55354509</wfw:commentRss>
    </item>
    <item>
      <title>An RxJS to Rx.NET bridge</title>
      <description>&lt;p&gt;&lt;em&gt;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.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Javascript is (almost) everywhere, literally.&lt;/p&gt;
&lt;p&gt;Not in everyone's minds though, which is only around &lt;a href="https://sites.google.com/site/pydatalog/pypl/PyPL-PopularitY-of-Programming-Language"&gt;7% according to the PYPL index&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Yet, Microsoft is pushing a lot on that front, particularly in Metro apps where the documentation shows JavaScript examples first. Subjectively, I&amp;rsquo;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&amp;nbsp;of the full JavaScript ecosystem, compared to the .NET counterpart.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;JavaScript ?&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://www.youtube.com/watch?v=hQVTIJBZook"&gt;Quirkiness of the language aside&lt;/a&gt;, things are going in a good direction -- particularly for large applications -- &lt;a href="http://www.typescriptlang.org/"&gt;with TypeScript&lt;/a&gt;, where type safety is introduced, among other things.&lt;/p&gt;
&lt;p&gt;Arguably, JavaScript is not very good a parallelism (which is &lt;strong&gt;very&lt;/strong&gt; different from asynchrony), mainly because it is single-threaded. There are ways around it, like using Web Workers, but this is bare-metal isolated parallelism, where everything needs to be done by hand. Maybe soon enough, we&amp;rsquo;ll end up with someone reinventing a .NET Remoting (or DCOM) look alike to address these issues.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;re going in a multi-core CPU direction, because processors scaling up seems to have slowed down quite a bit, and that scaling out is now the trend. The immutability trend seems to rise here and there to embrace this change, C# hints at taking that route with &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx"&gt;BCL&amp;rsquo;s immutable collections&lt;/a&gt;, and F# has it at its core.&lt;/p&gt;
&lt;p&gt;I foresee JavaScript lagging behind in that regard, but maybe that&amp;rsquo;s not a problem for now because it is used as an HTML back-end (and used it for this only&amp;nbsp;for the time being). We still need to address a lot of concerns with&amp;nbsp;raw performance, particularly when applications are not just displaying data, but are actually performing a lot of business computation on the client side.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Mixing C# and JavaScript&lt;/h2&gt;
&lt;p&gt;Fortunately, there is a very good way to do actual parallelism in Metro apps because of two things :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;JavaScript can call WinMD files code&lt;/li&gt;
&lt;li&gt;C# can expose code as WinMD files&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and in C#, there is Rx.NET that excels at mixing both asynchrony and parallelism. It is very easy to share and use immutable data using Rx and its Query based programming which makes it a good fit.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s actually pretty easy to create a mixed environments application :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Create a WinJS app&lt;/li&gt;
&lt;li&gt;Create a C# Windows Runtime Component, which creates a WinMD file&lt;/li&gt;
&lt;li&gt;Add a reference to the WinMD project in the WinJS project&lt;/li&gt;
&lt;li&gt;Call some code, and voila !&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Sounds too good to be that easy ?&amp;nbsp;Yeah, you&amp;rsquo;re actually right&amp;hellip;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Bridging RxJS and Rx.NET&lt;/h2&gt;
&lt;p&gt;Microsoft&amp;rsquo;s preferred way for exchanging messaging is through events. Even in WinMD type definitions, and pretty much all APIs in WinRT expose some sort of .NET like events.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;m not a big fan of events, for subscription lifetime, memory management, composition, delegation, &amp;hellip; I&amp;rsquo;m transforming them into Rx observable&amp;nbsp;where ever I can, and being able to have a common way&amp;nbsp;for exchanging asynchronous&amp;nbsp;notifications, using&amp;nbsp;multi-valued returning functions,&amp;nbsp;between both worlds seems a pretty good way to go.&lt;/p&gt;
&lt;p&gt;Both RxJS and Rx.NET seem to share the same notification&amp;nbsp;grammar, meaning that it is should be very easy to map between the two.&lt;/p&gt;
&lt;p&gt;But there is a problem with all this, being that JavaScript objects, as far as I know,&amp;nbsp;cannot be marshaled through to .NET. Only WinMD exposed types, primitives and delegates can. If you try to pass a Javascript object, you&amp;rsquo;ll be greeted with a Type Mismatch exception&amp;hellip;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Exposing an RxJS observable to Rx.NET&lt;/h2&gt;
&lt;p&gt;The idea is to be able to expose an RxJS observable to an Rx.NET C# observer, and subscribe to it.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: Excuse my JavaScript, I&amp;rsquo;m probably using it somehow the wrong way&amp;hellip; Feel free to correct me !&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;First, here is the JavaScript&amp;nbsp;observable we want to subscribe to :&lt;/p&gt;
&lt;pre&gt;var observable = Rx.Observable.return(42);&lt;/pre&gt;
&lt;p&gt;To be able to pass this around we need to expose a way to subscribe to that observable inside JavaScript, but allow for C# to provide onNext, onError and onCompleted handlers, but also a way to dispose the created subscription :&lt;/p&gt;
&lt;pre class="brush: javascript"&gt;Rx.Observable.prototype.toWrapper = function () {
        var parent = this;
        return new Umbrella.ObservableWrapper(
            function (onNext, onError, onCompleted) {
                var subscription = parent.subscribe(
                   onNext, 
                   function (e) { return onError(e.toString()); },
                   onCompleted
                );

                return function () { subscription.dispose(); }
            }
        );
    }; 
    &lt;/pre&gt;
&lt;p&gt;For the same reasons we can&amp;rsquo;t pass the observable directly to C#, we can&amp;rsquo;t pass the subscription returned by to subscribe back to C#. We also can&amp;rsquo;t pass the exception as-is.&lt;/p&gt;
&lt;p&gt;The trick here is to provide a first function that create the subscription, and return another that disposes it.&lt;/p&gt;
&lt;p&gt;The ObservableWrapper class is a WinMD exposed C# class that takes this form :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public sealed class ObservableWrapper
    {
        private SubscribeHandler _subscribe;
&lt;/pre&gt;
&lt;pre class="brush: c-sharp"&gt; 
        public ObservableWrapper(SubscribeHandler subscribe)
        {
            _subscribe = subscribe;
        }
&lt;/pre&gt;
&lt;pre class="brush: c-sharp"&gt; 
        internal IObservable&amp;lt;object&amp;gt; AsObservable()
        {
            return Observable.Create&amp;lt;object&amp;gt;(o =&amp;gt; {
                var disposeAction = _subscribe(
                    v =&amp;gt; o.OnNext(v), 
                    e =&amp;gt; o.OnError(new Exception(e.ToString())),
                    o.OnCompleted
                );
 
                return Disposable.Create(() =&amp;gt; disposeAction());
            });
        }
    }
    &lt;/pre&gt;
&lt;p&gt;The wrapper is created with a delegate that calls subscribe, and the observer is decomposed as three lambdas for the notifications. The subscribe delegate create a delegate that will dispose the subscription on the JavaScript side, when the C# observable will be disposed.&lt;/p&gt;
&lt;p&gt;Also note that the class is sealed, and that the AsObservable method is internal, because it exposes .NET only types and will only be used from .NET code.&lt;/p&gt;
&lt;p&gt;Next, C# methods can then take ObservableWrapper instances as parameters, which can be subscribed to :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public void DoStuff(ObservableWrapper wrapper)
{
   var s = 
      wrapper
       .AsObservable()
       .Subscribe(
          v =&amp;gt; Debug.WriteLine(v), 
          e =&amp;gt; Debug.WriteLine(e),
          () =&amp;gt; Debug.WriteLine("Completed")
       );
}
&lt;/pre&gt;
&lt;p&gt;It can then used like this, on the JavaScript side :&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre class="brush: javascript"&gt;var foo = new MyApp.Foo(); 
foo.doStuff(observable.toWrapper());&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;All this works pretty well !&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ll probably talk on how to do it the other way around in another blog post, as there are some other tricks to use to make this work.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/01/22/An-RxJS-to-RxNET-bridge.aspx</link>
      <comments>http://jaylee.org/post/2013/01/22/An-RxJS-to-RxNET-bridge.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=8d041da6-0c8c-46f9-a38b-745ca5c9b323</guid>
      <pubDate>Tue, 22 Jan 2013 21:19:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=8d041da6-0c8c-46f9-a38b-745ca5c9b323</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=8d041da6-0c8c-46f9-a38b-745ca5c9b323</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/01/22/An-RxJS-to-RxNET-bridge.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=8d041da6-0c8c-46f9-a38b-745ca5c9b323</wfw:commentRss>
    </item>
    <item>
      <title>ReaderWriterLockSlim on Windows Phone 8 and the seemingly random MethodAccessException</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: Don't use the &lt;a href="http://msdn.microsoft.com/en-us/library/System.Threading.ReaderWriterLockSlim.aspx"&gt;ReaderWriterLockSlim&lt;/a&gt;&amp;nbsp;class&amp;nbsp;on Windows Phone 8 RTM, it has a bug&amp;nbsp;that appears only under contention.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Windows Phone 8&amp;rsquo;s move to the NT kernel has had a lot of advantages for the developer, such as the move to the same .NET CLR as the Desktop Windows, but also the ability to have multi-core based environment.&lt;/p&gt;
&lt;p&gt;More specifically, there is one access synchronization &amp;ndash; the &lt;a href="http://msdn.microsoft.com/en-us/library/System.Threading.ReaderWriterLockSlim.aspx"&gt;ReaderWriterLockSlim&lt;/a&gt; &amp;ndash; which makes a lot of sense in real multi-core environment.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve been using this class to synchronize access to a dictionary abstraction&amp;nbsp;for performance reasons and also for legacy reasons,&amp;nbsp;since that the &lt;a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx"&gt;Concurrent Collections&lt;/a&gt; are available. Note that we do have a new tool in the toolbox, the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx"&gt;BCL Immutable Collections&lt;/a&gt;, that are&amp;nbsp;becoming my new preferred way for creating collections.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;The (seemingly) random System.MissingMethodException&lt;/h2&gt;
&lt;p&gt;After moving a project to Windows Phone 8, I started seeing this &lt;a href="http://msdn.microsoft.com/en-us/library/system.methodaccessexception.aspx"&gt;MethodAccessException&lt;/a&gt; sporadically, seemingly without any reason :&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span style="font-family: courier new,courier;"&gt;[System.MethodAccessException]&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;Attempt by method 'System.Threading.ReaderWriterLockSlim.WaitOnEvent(System.Threading.EventWaitHandle, UInt32 ByRef, TimeoutTracker)' to access method 'System.Threading.WaitHandle.WaitOne(Int32, Boolean)' failed.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Which seems a bit odd.&lt;/p&gt;
&lt;p&gt;I was able to reproduce the issue this way :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;var r = new ReaderWriterLockSlim();
r.TryEnterUpgradeableReadLock(-1); 
r.TryEnterWriteLock(-1);
ThreadPool.QueueUserWorkItem(_ =&amp;gt; { r.TryEnterWriteLock(-1); });&lt;/pre&gt;
&lt;p&gt;With this code pasted in the constructor of the app.xaml.cs file of an empty app.&lt;/p&gt;
&lt;p&gt;This means that until there is actual contention on the lock, the bug will not show up. This makes it show up seemingly randomly.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;A bit of geeky digging&lt;/h2&gt;
&lt;p&gt;As always, I just can't let an issue like this not deeply understood, and I've dug a bit deeper to understand why this is happening.&lt;/p&gt;
&lt;p&gt;In Windows Phone 8, the ReaderWriterLockSlim type is in the System.Core.dll assembly, and considering the exception stack trace and message, the ReaderWriterLockSlim.WaitOnEvent method is trying to access the WaitHandle.WaitOne(Int32, Boolean) method which is located in the mscorlib.dll assembly.&lt;/p&gt;
&lt;p&gt;The problem is actually pretty simple: The WaitHandle.WaitOne(Int32, Boolean) method is declared as private in another assembly, making the runtime fail when linking the method.&lt;/p&gt;
&lt;p&gt;This brings another interesting insight on how&amp;nbsp;Microsoft handles the Framework, because this code could not have been compiled using the current set of assemblies. Somehow, the System.Core.dll was built using a different mscorlib.dll which has this method either public or most probably&amp;nbsp;internal (because mscorlib.dll has the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx"&gt;InternalsVisibleTo&lt;/a&gt;("System.Core") attribute set).&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;A workaround&lt;/h2&gt;
&lt;p&gt;To my knowledge, this issue is present in Windows Phone 8 RTM (Apollo), and I&amp;rsquo;ve not been able to validate that this is still present in the Portico update.&lt;/p&gt;
&lt;p&gt;For the time being, I&amp;rsquo;ve moved back to a Monitor based synchronization mechanism until this gets fixed.&lt;/p&gt;
&lt;p&gt;So in short, don&amp;rsquo;t use ReaderWriterLockSlim on Apollo.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/01/13/ReaderWriterLockSlim-on-Windows-Phone-8-and-the-seemingly-random-MethodAccessException.aspx</link>
      <comments>http://jaylee.org/post/2013/01/13/ReaderWriterLockSlim-on-Windows-Phone-8-and-the-seemingly-random-MethodAccessException.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=69f2e4c6-dd3f-44a0-96b9-bcdaca2f8f28</guid>
      <pubDate>Sun, 13 Jan 2013 15:02:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows Phone Dev</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=69f2e4c6-dd3f-44a0-96b9-bcdaca2f8f28</pingback:target>
      <slash:comments>3</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=69f2e4c6-dd3f-44a0-96b9-bcdaca2f8f28</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/01/13/ReaderWriterLockSlim-on-Windows-Phone-8-and-the-seemingly-random-MethodAccessException.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=69f2e4c6-dd3f-44a0-96b9-bcdaca2f8f28</wfw:commentRss>
    </item>
    <item>
      <title>Toying around with F# Queries, Rx, Portables Libraries, Windows [Phone] 8 and the Zip operator</title>
      <description>&lt;p&gt;Agreed, that&amp;rsquo;s a lot of keywords. Yet, they fit one another in a very interesting way.&lt;/p&gt;
&lt;p&gt;I find more and more that F#, particularly regarding the way my development trends are going, is getting more and more of a fit regarding the immutability and flexibility needs.&lt;/p&gt;
&lt;p&gt;Given that, I thought I&amp;rsquo;d give a try at running some F# Query Expressions using custom Rx operators, on Windows Phone 8, using Portable Libraries.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;Getting F# to run on Windows Phone 8&lt;/h2&gt;
&lt;p&gt;Interestingly, the F# team made a &lt;a href="http://msdn.microsoft.com/en-us/library/gg597391.aspx"&gt;portable library&lt;/a&gt;&amp;nbsp;version of their runtime, so that it can run under the intersection of .NET 4.5, Windows Store Apps and Silverlight 5 frameworks. Windows Phone 8 projects accept this intersection, which make F# available to work with.&lt;/p&gt;
&lt;p&gt;That was easy.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Getting Rx to run on F#&amp;rsquo;s PLib intersection&lt;/h2&gt;
&lt;p&gt;That one is a bit more tricky. Out of the box, &lt;a href="http://msdn.microsoft.com/en-us/data/gg577609.aspx"&gt;Rx&lt;/a&gt;&amp;nbsp;supports a different PLib frameworks intersection, being .NET 4.5 and Windows Store Apps.&lt;/p&gt;
&lt;p&gt;Fortunately, the &lt;a href="http://rx.codeplex.com/"&gt;Rx team published the source code&lt;/a&gt; of the library, making this experiment a lot easier to do.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve updated a bit the Rx sources to match a set of new defines :&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;DefineConstants&amp;gt;
$(DefineConstants);NO_RXINTERFACES;PREFER_ASYNC;
HAS_APTCA;NO_HASHSET;NO_CDS;NO_SEMAPHORE;NO_STOPWATCH;
NO_REMOTING;NO_SERIALIZABLE;NO_THREAD;PLIB
&amp;lt;/DefineConstants&amp;gt;&lt;/pre&gt;
&lt;p&gt;I&amp;rsquo;ve also changed the PLib profile&amp;nbsp;from Profile7 and Profile47, to match the same profile as the F# portable library. There&amp;rsquo;s actually a new define I introduced, NO_SEMAPHORE, because that new profile does not support the SemaphoreSlim class.&lt;/p&gt;
&lt;p&gt;I had to make a small update to the code to make that code Semaphore-less, if you&amp;rsquo;re interested let me know, I&amp;rsquo;ll share that.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Playing with the F# Query Expressions and Rx&lt;/h2&gt;
&lt;p&gt;I&amp;rsquo;ve come across an interesting article from &lt;a href="http://mnajder.blogspot.ca/2011/09/when-reactive-framework-meets-f-30.html"&gt;Marcin Najder about F# 3.0 and Query Expressions&lt;/a&gt; using the Reactive Extensions and this got me started.&lt;/p&gt;
&lt;p&gt;The interesting side is to be able to have comprehensions that simplify the writing of queries that contain LINQ or Rx operators that may not be supported by C#, such as IObservable.Take() :&lt;/p&gt;
&lt;pre&gt;type Dummy() = 
 
        let rxquery = new RxQueryBuiler()
        let obs = new ObsBuiler()
 
        let values =
            obs {
                for value in [0..15] do
                    yield value
            }
           
        member this.Foo = 
            rxquery {
                for value in values do
                where (value &amp;gt; 1)
                select value
                take 10 into trimmed
                select trimmed 
            }
    &lt;/pre&gt;
&lt;p&gt;The Foo property can be used directly from a C# program, and observed like any other IObservable instance.&lt;/p&gt;
&lt;h2&gt;&lt;span style="font-family: Calibri;"&gt;The ZipLike custom operator&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;With Rx and their enumerable counterparts (such as Linq), the &lt;a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.zip(v=VS.103).aspx"&gt;Zip operator&lt;/a&gt; allows to get two streams of values and produce another using each tuple of values.&lt;/p&gt;
&lt;p&gt;The problem with this operator is that in C# it cannot be written using the &amp;ldquo;from xx in yy&amp;rdquo;&amp;nbsp;LINQ syntax, because there is no keyword for it, and the language does not allow the creation of new ones (though some are &lt;a href="http://social.msdn.microsoft.com/Forums/en/rx/thread/155cd697-5341-465c-98c3-268793c4a653"&gt;trying to get that into future C# versions&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;There&amp;nbsp;are no examples or documentation anywhere to use a custom Zip operator (using the &lt;a href="http://msdn.microsoft.com/en-us/library/hh289776.aspx"&gt;CustomOperation.IsLikeZip&lt;/a&gt;&amp;nbsp;property), so digging a bit into the F# test suite got me started on how to use it.&lt;/p&gt;
&lt;p&gt;So, instead of writing a Zip like this :&lt;/p&gt;
&lt;pre&gt;o1.Zip(o2, (lv, rv) =&amp;gt; new Tuple(lv, rv));&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;It can be written like this in F#, by defining a custom zip operator :&lt;/p&gt;
&lt;pre&gt;    let values2 =
        obs {
            for value in [5..20] do
                yield value
        }&lt;/pre&gt;
&lt;pre&gt;    member this.Combined = 
        rxquery {
            for test in values do
            zip test2 in values2
            select (test, test2)
        }&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;This returns a simple tuple for the combined values.&lt;/p&gt;
&lt;p&gt;But this also has the advantage of providing what the &lt;a href="http://msdn.microsoft.com/en-us/library/bb383976(v=VS.100).aspx"&gt;C# let keyword&lt;/a&gt; does, by creating query variables :&lt;/p&gt;
&lt;pre&gt;        member this.Combined = 
            rxquery {
                for test in values do
                zip test2 in values2
                let values = (test * 2, test2)
                where (fst(values) &amp;gt; 5)
                select (test, test2)
            }
    &lt;/pre&gt;
&lt;p&gt;There is no need to create temporary anonymous types to forward the state of the query to downstream Rx operators manually.&lt;/p&gt;
&lt;p&gt;Cool stuff, really.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2013/01/02/Toying-around-with-FSharp-Queries-Rx-Portables-Libraries-Windows-Phone-8-and-the-Zip-operator.aspx</link>
      <comments>http://jaylee.org/post/2013/01/02/Toying-around-with-FSharp-Queries-Rx-Portables-Libraries-Windows-Phone-8-and-the-Zip-operator.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=2e467560-704b-4466-94ca-62182bd2a061</guid>
      <pubDate>Wed, 02 Jan 2013 22:42:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows Phone Dev</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=2e467560-704b-4466-94ca-62182bd2a061</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=2e467560-704b-4466-94ca-62182bd2a061</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2013/01/02/Toying-around-with-FSharp-Queries-Rx-Portables-Libraries-Windows-Phone-8-and-the-Zip-operator.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=2e467560-704b-4466-94ca-62182bd2a061</wfw:commentRss>
    </item>
    <item>
      <title>Reading the content of the Xap/Appx and IsoStore in Windows [Phone] 8</title>
      <description>&lt;p&gt;In Windows Phone 8, things got better of the front of reading the file system. It&amp;rsquo;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)&amp;nbsp;to access directly before.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Reading the app package content files&lt;/h2&gt;
&lt;p&gt;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 &lt;a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx"&gt;the IsolatedStorage&lt;/a&gt;, but really did not have access to the content of the Xap, except for some location such as images &lt;a href="http://www.developer.nokia.com/Community/Wiki/How_to_access_Application_Manifest_(WMAppManifest.xml)_file_at_runtime"&gt;or XmlDocument&lt;/a&gt; and the SQL CE engine &lt;a href="http://msdn.microsoft.com/en-us/library/hh202861%28v=vs.92%29.aspx"&gt;using the appdata:/ scheme&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Things have changed in Windows Phone 8, and here&amp;rsquo;s how to read the WMAppManifest.xml file by yourself :&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;   var file = await StorageFile.GetFileFromPathAsync(
      Path.Combine(
         Windows.ApplicationModel.Package.Current.InstalledLocation.Path,   
         "WMAppManifest.xml"
      ) 
   );

   using (var stream = new StreamReader(await file.OpenStreamForReadAsync()))
   {
      var content = await stream.ReadToEndAsync();
   }&lt;/pre&gt;
&lt;p&gt;That way, you can access anything located in your package, and use it like any other file. Also note that this technique is also working on Windows 8.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Reading the content of the IsolatedStorage&lt;/h2&gt;
&lt;p&gt;The IsolatedStorage class is just a wrapper around the file system that was introduced in .NET a while back, but since it is now possible to access the file system using WinRT, it is possible to read the isolated storage folder content directly.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s just a matter of using &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh700361.aspx"&gt;Windows.Storage.ApplicationData.Current.LocalFolder&lt;/a&gt; and replicating the code above, which will make for a very portable code between Windows 8 and Windows Phone 8.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2012/12/20/Reading-the-content-of-the-XapAppx-and-IsoStore-in-Windows-Phone-8.aspx</link>
      <comments>http://jaylee.org/post/2012/12/20/Reading-the-content-of-the-XapAppx-and-IsoStore-in-Windows-Phone-8.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=5ed8b4f7-c828-4564-8e5f-f3a0c4d645bf</guid>
      <pubDate>Thu, 20 Dec 2012 09:57:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows Phone Dev</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=5ed8b4f7-c828-4564-8e5f-f3a0c4d645bf</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=5ed8b4f7-c828-4564-8e5f-f3a0c4d645bf</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2012/12/20/Reading-the-content-of-the-XapAppx-and-IsoStore-in-Windows-Phone-8.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=5ed8b4f7-c828-4564-8e5f-f3a0c4d645bf</wfw:commentRss>
    </item>
    <item>
      <title>DataBinding performance in WinRT and the Bindable attribute</title>
      <description>&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&lt;em&gt;tl;dr: The Bindable attribute can be placed on standard C# classes in Metro Apps&amp;nbsp;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.&lt;/em&gt;&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;Databinding in WPF/WinRT is very easy to use. Just put the name of the field you want to bind, set the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx"&gt;DataContext&lt;/a&gt;, 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.&lt;/p&gt;
&lt;p&gt;In WPF and Silverlight, this is fairly easy to do because everything is in managed code. Resolving that data&amp;nbsp;member was performed using a bit of type Reflection, where the string "&lt;span style="font-family: courier new,courier;"&gt;{Binding SomeValue}&lt;/span&gt;" would result in a sequence of &lt;a href="http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx"&gt;Type.GetProperty&lt;/a&gt; to get a &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx"&gt;PropertyInfo&lt;/a&gt; instance, then call &lt;a href="http://msdn.microsoft.com/en-us/library/hh194385.aspx"&gt;GetValue&lt;/a&gt; to get the actual value.&lt;/p&gt;
&lt;p&gt;But in WinRT, all this is a lot different, mainly because WinRT is purely native and there is no reflection or metadata there.&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&lt;/p&gt;
&lt;h2&gt;Reflection for C#/XAML apps using WinRT&lt;/h2&gt;
&lt;p&gt;How does that work then? Well, that&amp;rsquo;s where some magic happens during the compilation of a C#/XAML project, a subject that &lt;a href="http://jaylee.org/post/2012/03/07/Xaml-integration-with-WinRT-and-the-IXamlMetadataProvider-interface.aspx"&gt;I covered a while back&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The compilation process parses the Xaml files to find nodes that reference actual C# or WinMD defined types, and generates a fairly big class that implements the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.markup.ixamlmetadataprovider.aspx"&gt;IXamlMetadataProvider&lt;/a&gt; class. This class will provide detailed information about the types such as how to create them, their members, whether they are read-only or not, enum values, if there is a content property, etc&amp;hellip;&lt;/p&gt;
&lt;p&gt;This generated class is basically a static reflection engine for WinRT. At runtime, this class is provided to WinRT which in turn, calls it to determine what to do with the nodes it just parsed.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;The magic with DataBinding POCO classes&lt;/h2&gt;
&lt;p&gt;There&amp;rsquo;s actually one interesting scenario, when using databinding POCO classes. Let&amp;rsquo;s say you&amp;nbsp;write this:&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;TextBlock x:Name=&amp;rdquo;test&amp;rdquo; Text={Binding MyValue}&amp;rdquo; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Create the following class:&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;public class MyClass
{
   public string MyValue { get; set; }
}&lt;/pre&gt;
&lt;p&gt;And DataBind it using this code :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;test.DataContext = new MyClass { MyValue = &amp;ldquo;Hello world !&amp;rdquo; };&lt;/pre&gt;
&lt;p&gt;Everything will work as expected.&lt;/p&gt;
&lt;p&gt;But if you look at the generated IXamlMetadataProvider class, you&amp;rsquo;ll notice that there no reference to the MyClass type.&lt;/p&gt;
&lt;p&gt;I stated previously that WinRT can&amp;rsquo;t do reflection, so how does that work? Simple. .NET Runtime magic !&lt;/p&gt;
&lt;p&gt;Digging a bit deeper, by placing a breakpoint behind the C# auto property, we&amp;rsquo;ll find this stack trace:&lt;/p&gt;
&lt;pre class="brush: text"&gt;--&amp;gt; MyApp.exe!MyApp.MyClass.MyValue.get()
    [Native to Managed Transition]
    mscorlib.dll!System.Runtime.InteropServices.WindowsRuntime.CustomPropertyImpl.InvokeInternal(object target, object[] args, bool getValue)
    mscorlib.dll!System.Runtime.InteropServices.WindowsRuntime.CustomPropertyImpl.GetValue(object target)
    [Native to Managed Transition]
    [Managed to Native Transition]
    MyApp.exe!MyApp.MainPage.Test()
&amp;nbsp;
&amp;nbsp;
&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;The runtime provides a way for WinRT to actually be able to perform reflection on arbitrary types that are not known at compile time by the IXamlMetadataProvider implementation, using the internal CustomPropertyImpl class.&lt;/p&gt;
&lt;p&gt;This is completely transparent to the developer, and works very efficiently.&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&lt;span style="font-size: small; font-family: Calibri;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;Adding a POCO to the IXamlMetadataProvider&lt;/h2&gt;
&lt;p&gt;Knowing that DataBinding also works in a completely native environment using C++/CX, tells some very interesting information.&lt;/p&gt;
&lt;p&gt;To be able to databind a type in a C++/XAML app, it is required to place the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.data.bindableattribute.aspx"&gt;Bindable&lt;/a&gt; attribute. This will force the C++ compiler to generate code that performs the same static reflection class found in C#/Xaml apps. A similar IXamlMetadataProvider implementing class will be generated with this metadata, allowing the Xaml parser to work properly, the same way it does&amp;nbsp;with C#.&lt;/p&gt;
&lt;p&gt;When looking at the documentation for Bindable, here what can be read:&lt;/p&gt;
&lt;pre&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;ldquo;Specifies&amp;nbsp;that&amp;nbsp;a&amp;nbsp;type&amp;nbsp;defined&amp;nbsp;in&amp;nbsp;C++&amp;nbsp;can&amp;nbsp;be&amp;nbsp;used&amp;nbsp;for&amp;nbsp;binding.&amp;rdquo;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Which implies that it should only be used for C++ created types.&lt;/p&gt;
&lt;p&gt;Yet, because this attribute is defined in WinRT, it can be used on C# classes, and surprise, classes marked with it also get added to the generated IXamlMetadataProvider !&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;This attribute can also be used to mark types as&amp;nbsp;Bindable when provided&amp;nbsp;in another assembly, but that are never referenced in Xaml.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;m a big fan of code generation over reflection, particularly if what&amp;rsquo;s being reflected upon is known at compile time. I firmly believe that it is most of the time a way better use of CPU power to perform this code generation a compile time, over doing it countless times on the client at runtime.&lt;/p&gt;
&lt;p&gt;This is why I&amp;rsquo;ll favor generating code, and this "Bindable" finding sound like music to my ears&amp;hellip;&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;&amp;nbsp;&lt;/h2&gt;
&lt;h2&gt;Profiling the Binding performance using Reflected and Bindable marked types&lt;/h2&gt;
&lt;p&gt;But let&amp;rsquo;s be clear. Microsoft did not think this technique would be interesting, because they would have otherwise told to add that attribute to classes. Still, let&amp;rsquo;s see how both binding infrastructure perform.&lt;/p&gt;
&lt;p&gt;Before that, there are actually two things to consider.&lt;/p&gt;
&lt;p&gt;First, the generated code for the IXamlMetadataProvider is not free. Even if it is mostly non-conditional, it still needs to be executed when the app starts to build the type definitions to provide to the WinRT Xaml engine. If this class grows very big, this may adversely impact the performance of the metadata lookup. A big switch/case on strings construct is translated into a standard &lt;a href="http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx"&gt;IDictionary&amp;lt;string, int&amp;gt;&lt;/a&gt;, and reading this dictionary is not free.&lt;/p&gt;
&lt;p&gt;Second, if there are lots of bindable types, even if the provider is composed of a single big switch/case and lots of small get/set methods, this means that this big method will need to be JITed. This can take a substantial amount of time at the startup of the app. This begs for NGEN though, as &lt;a href="http://jaylee.org/post/2012/11/24/Reducing-apps-startup-time-with-Pre-JITing-and-NGEN-on-a-Surface-RT.aspx"&gt;I&amp;rsquo;ve discussed in a previous article&lt;/a&gt;, to eliminate this overhead.&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&lt;span style="font-size: small; font-family: Calibri;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;h3&gt;Testing the startup speed&lt;/h3&gt;
&lt;p&gt;Testing the startup speed can be done using code generation using T4. Considering an app that has around 30 databind-able types, all comprised of 15 fields, here&amp;rsquo;s the startup time up to the data observed on the screen of a Surface RT:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reflection, 1.9s with JIT, 1.8s with NGEN&lt;/li&gt;
&lt;li&gt;Bindable, 3.1s with JIT, 1.8s with NGEN&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Testing the binding speed&lt;/h3&gt;
&lt;p&gt;Testing the binding speed be done using two simple types (one with the Bindable attribute, the other without), with one field, both databound to a TextBlock Text property. The loop is about setting 5000 times the DataContext to a new instance of the type:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reflection: 2.00s with a string, 2.45s with an int&lt;/li&gt;
&lt;li&gt;Bindable: 1.78s with a string, 2.20s with an int&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This makes for improvement of about 10%, which is interesting, particularly considering the fact that ARM tablets are not that powerful.&lt;/p&gt;
&lt;p&gt;Unsurprisingly, since everything is passed out as an object both in the IXamlMetadataProvider&amp;nbsp;and CustomPropertyImpl classes, binding to value types is a bit more expensive because of boxing operations.&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;I'll provide the code for these two basic&amp;nbsp;tests, if someone's interested.&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 10pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Is this good for you ?&lt;/h2&gt;
&lt;p&gt;It may or may not be useful to you, depending on how much the non-NGENed startup is important for you, but also how much you rely on DataBinding.&lt;/p&gt;
&lt;p&gt;I for one think that an added second to the startup to gain a rough 10% in binding speed seems a fairly reasonable deal, particularly when NGEN passes by afer a while to suppress this overhead.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Remember that an app only has 16.6ms to perform operations on the dispatcher&lt;/strong&gt; between screen refreshes to maintain 60 Frames per second and keep a smooth user experience.&lt;/p&gt;
&lt;p&gt;On an ARM tablet, added to other performance tweaks, this can overall make a difference.&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2012/11/26/DataBinding-performance-in-WinRT-and-the-Bindable-attribute.aspx</link>
      <comments>http://jaylee.org/post/2012/11/26/DataBinding-performance-in-WinRT-and-the-Bindable-attribute.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=ee9f174d-0d33-4ad7-b413-8f18038c576d</guid>
      <pubDate>Mon, 26 Nov 2012 20:51:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=ee9f174d-0d33-4ad7-b413-8f18038c576d</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=ee9f174d-0d33-4ad7-b413-8f18038c576d</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2012/11/26/DataBinding-performance-in-WinRT-and-the-Bindable-attribute.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=ee9f174d-0d33-4ad7-b413-8f18038c576d</wfw:commentRss>
    </item>
    <item>
      <title>Reducing apps startup time with Pre-JITing and NGEN on a Surface RT</title>
      <description>&lt;p&gt;&lt;em&gt;TL;DR: The JIT can take over a third of the startup time of a managed Metro App, and using&amp;nbsp;Native Image Generation (NGEN)&amp;nbsp;can greatly improve the startup time of these apps. There is also a way to check for these native images to act accordingly.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;A while back, &lt;a href="http://jaylee.org/post/2012/06/11/Improving-the-Startup-Time-of-Xaml-Metro-Style-Apps-with-Multicore-JIT.aspx"&gt;I&amp;rsquo;ve had the chance to work with the guys that are behind the Pre-JIT &lt;/a&gt;feature of the CLR 4.5 for&amp;nbsp;Metro Apps. Back then, I was only able to work on x86/x64 architectures, as ARM/Windows RT devices were not available.&lt;/p&gt;
&lt;p&gt;Now that the Surface RT devices&amp;nbsp;are available, we&amp;rsquo;re facing quite a few challenges in terms of code execution performance, and I&amp;rsquo;m going to discuss a few tips and tricks about the Managed Code JIT on Windows RT.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Profiling a slow starting app on a Surface RT&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;Profiling such an app that starts slowly is very interesting, when looking a the &lt;a href="http://msdn.microsoft.com/en-us/library/z9z62c29.aspx"&gt;Visual Studio profiler&lt;/a&gt;, where during these 17 seconds, about a third is spent in a &amp;ldquo;clr.dll&amp;rdquo; module in exclusive time (time spent only in this module and not its descendants). This is a very big number.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;This JIT phase is expected though, and is since .NET 1.0. Microsoft chose not to JIT metro&amp;nbsp;apps on installation supposedly to improve the user's interaction flow with apps, and did not choose to make it in the cloud like the Windows Phone team did, starting from Windows Phone 8. The drawback of this approach&amp;nbsp;is that managed code apps do have an extremely poor first launch experience, where the JIT kicks in every time.&lt;/p&gt;
&lt;p&gt;The good news is that there are workaround for this slow startup, Pre-JIT and NGEN.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Pre-JITing applications&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://jaylee.org/post/2012/06/11/Improving-the-Startup-Time-of-Xaml-Metro-Style-Apps-with-Multicore-JIT.aspx"&gt;Pre-JIT&lt;/a&gt; is based on profiling how an app JITs code, then creating a file out of it that can be bundled with the final app package. In later startups of the app, that file is used of JIT code ahead of time, substantially improving the app&amp;rsquo;s startup time.&lt;/p&gt;
&lt;p&gt;Yet, this technique is not the panacea, because it still requires the CPU to JIT code every time, preventing the rest of the app to use that CPU-time for some other useful tasks.&lt;/p&gt;
&lt;p&gt;While this profile technique works like a charm on Windows 8 desktop, I&amp;rsquo;ve yet to notice any difference in the startup time of apps on Windows RT. I&amp;rsquo;m not sure if it&amp;rsquo;s the CPU that&amp;rsquo;s not powerful enough to JIT ahead of the normal execution path, or if it&amp;rsquo;s simply not used at all.&lt;/p&gt;
&lt;p&gt;Interestingly, I&amp;rsquo;ve been able to generate that profile on a Surface device, but that&amp;rsquo;s pretty much it.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;NGEN on Windows RT&lt;/h2&gt;
&lt;p&gt;Fortunately, apps are NGENed roughly after 24 hours. This technique, which has been around since .NET 1.0, has the ability to take managed code and generate a &amp;ldquo;native&amp;rdquo; image which is basically a fully JITed assembly that targets the current CPU architecture.&lt;/p&gt;
&lt;p&gt;That same app that takes 17 seconds to start and be useable drops down to 12 seconds. This makes the startup a lot more interesting! (12 seconds is still not acceptable, but using other optimizations like using the 4 logical cores, that same app is now down to 8 second, which is a lot better)&lt;/p&gt;
&lt;p&gt;This NGEN tool is ran as part of a &amp;ldquo;Maintenance Task&amp;rdquo;, located in the standard Windows Scheduler. It can be found when searching for &amp;ldquo;Schedule tasks&amp;rdquo; in the start menu, then under &amp;ldquo;Microsoft / Windows / .NET Framework&amp;rdquo;. Right clicking and selecting Run for both &amp;ldquo;.NET Framework NGEN v4.0.30319&amp;rdquo; and &amp;ldquo;.NET Framework NGEN v4.0.30319 64&amp;rdquo; will generate native images for applications that have been run at least once for what seems to be about 10 to 15 seconds.&lt;/p&gt;
&lt;p&gt;On the Surface RT, generating these images can take quite some time depending on the size of the app. I&amp;rsquo;ve seen apps that take about 30 seconds to a minute to fully generate. Also note that there are space constraints, such as available free space. If your system drive has limited free space (such as below 1GB), NGEN will not generate anything.&lt;/p&gt;
&lt;p&gt;Microsoft recommends &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh994639.aspx"&gt;running this tool&lt;/a&gt; by hand using a command line, but I&amp;rsquo;ve yet to see it work properly on a Surface RT device&amp;hellip; Only running&amp;nbsp;the scheduled task manually actually generates native images.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Checking&amp;nbsp;for native images&lt;/h2&gt;
&lt;p&gt;Knowing that you&amp;rsquo;re running with or without native images can allow you to act differently to mitigate&amp;nbsp;the terrible initial startup time.&lt;/p&gt;
&lt;p&gt;The generated native images are located under the following folder:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span style="font-family: courier new,courier;"&gt;%LOCALAPPDATA%\Packages\[AppID]\AC\Microsoft\CLR_v4.0_32\NativeImages&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Testing for its presence is enough to guess it the app is running without JIT.&lt;/p&gt;
&lt;p&gt;The following code can tell you this :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;    private async Task IsNativeImage()
    {
        var source = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\..\\AC\\Microsoft\\";
            
        try
        {
            await StorageFolder.GetFolderFromPathAsync(source + "CLR_v4.0_32\\NativeImages");
            return true;
        }
        catch (Exception ex) { }

        try
        {
            await StorageFolder.GetFolderFromPathAsync(source + "CLR_v4.0\\NativeImages");
            return true;
        }
        catch (Exception ex) { }

        return false;
    }
&lt;/pre&gt;
&lt;p&gt;So when testing for your app&amp;rsquo;s performance, don&amp;rsquo;t forget to manually run NGEN&amp;nbsp;and create a JIT profile&amp;nbsp;!&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2012/11/24/Reducing-apps-startup-time-with-Pre-JITing-and-NGEN-on-a-Surface-RT.aspx</link>
      <comments>http://jaylee.org/post/2012/11/24/Reducing-apps-startup-time-with-Pre-JITing-and-NGEN-on-a-Surface-RT.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=85190a84-a680-414a-a55c-15bc87b1c873</guid>
      <pubDate>Sat, 24 Nov 2012 21:13:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=85190a84-a680-414a-a55c-15bc87b1c873</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=85190a84-a680-414a-a55c-15bc87b1c873</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2012/11/24/Reducing-apps-startup-time-with-Pre-JITing-and-NGEN-on-a-Surface-RT.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=85190a84-a680-414a-a55c-15bc87b1c873</wfw:commentRss>
    </item>
    <item>
      <title>Of Static Code Analysis, CA0001, WinMD files and C# Dynamic in Metro Style apps</title>
      <description>&lt;p&gt;&lt;em&gt;tl;dr: This article is about working around an &lt;a href="http://msdn.microsoft.com/en-us/library/3z0aeatx.aspx"&gt;FxCop &lt;/a&gt;internal&amp;nbsp;bug using the C# dynamic keyword, not exactly the way is was supposed to be used.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;With the release of Windows 8 and WinRT, developing in .NET requires adding references to the new &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh755822.aspx"&gt;WinMD file format&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This format is a .NET assembly look-alike, so look-alike that old ILDASM builds can open them.&lt;/p&gt;
&lt;p&gt;These files are only containing stubs, the definition of types&amp;nbsp;that come from WinRT, which is developed using native C++ code.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;WinMD files and Static Code Analysis&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/3z0aeatx.aspx"&gt;FxCop&lt;/a&gt;&amp;nbsp;is working rather fine with WinMD files in Metro style apps, except for one interest case, when compiling the following code :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;private static void SomeMethod()
{
   var b = new Button();
   b.Command = null;
}&lt;/pre&gt;
&lt;p&gt;Which fails with the following exception when analyzed by FxCop, using the &amp;ldquo;Microsoft Managed Recommended Rules&amp;rdquo;:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span style="font-family: courier new,courier;"&gt;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. &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;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&amp;hellip; Which is ironic since these attributes cannot be used in Metro style apps :) But still, this is a multi-framework analysis engine.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;A CA0001 workaround and the Dynamic keyword&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s how to do it :&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;private static void SomeMethod()
{
   #if DEBUG
   var b = new Button();
   #else
   dynamic b = new Button();
   #endif

   b.Command = null;
}&lt;/pre&gt;
&lt;p&gt;I &lt;em&gt;do&lt;/em&gt; 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&amp;nbsp;Analysis running to catch all other possible code issues.&lt;/p&gt;
&lt;p&gt;Having a &lt;a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx"&gt;dynamic&lt;/a&gt; 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.&lt;/p&gt;
&lt;p&gt;Here's what actually generated by the compiler, to evade FxCop scrutiny&amp;nbsp;:&lt;/p&gt;
&lt;pre class="brush: c-sharp"&gt;object b = new Button();
if (MainPage.o__SiteContainer0.&amp;lt;&amp;gt;p__Site1 == null)
{
   MainPage.o__SiteContainer0.&amp;lt;&amp;gt;p__Site1 = CallSite&amp;gt;.Create(Binder.SetMember(CSharpBinderFlags.None, "Command", typeof(MainPage), new CSharpArgumentInfo[]
   {
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), 
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null)
   }));
}
MainPage.o__SiteContainer0.&amp;lt;&amp;gt;p__Site1.Target(MainPage.o__SiteContainer0.&amp;lt;&amp;gt;p__Site1, b, null);&lt;/pre&gt;
&lt;p&gt;Having&amp;nbsp;the code&amp;nbsp;compiling using an actual static typing in Debug configuration leaves a bit of compile-time type checking, nonetheless.&lt;/p&gt;
&lt;p&gt;There should be a connect entry for this soon, if you'd like to follow-up.&lt;/p&gt;
&lt;p&gt;Happing dynamic hacking ! :)&lt;/p&gt;</description>
      <link>http://jaylee.org/post/2012/10/27/Of-Static-Code-Analysis-CA0001-WinMD-files-and-CSharp-Dynamic-in-Metro-Style-apps.aspx</link>
      <comments>http://jaylee.org/post/2012/10/27/Of-Static-Code-Analysis-CA0001-WinMD-files-and-CSharp-Dynamic-in-Metro-Style-apps.aspx#disqus_thread</comments>
      <guid>http://jaylee.org/post.aspx?id=7909136b-8fc7-4e1b-971d-5e23bd2f8562</guid>
      <pubDate>Sat, 27 Oct 2012 12:42:00 -0600</pubDate>
      <category>.NET</category>
      <category>Windows 8</category>
      <dc:publisher>jay</dc:publisher>
      <pingback:server>http://jaylee.org/pingback.axd</pingback:server>
      <pingback:target>http://jaylee.org/post.aspx?id=7909136b-8fc7-4e1b-971d-5e23bd2f8562</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://jaylee.org/trackback.axd?id=7909136b-8fc7-4e1b-971d-5e23bd2f8562</trackback:ping>
      <wfw:comment>http://jaylee.org/post/2012/10/27/Of-Static-Code-Analysis-CA0001-WinMD-files-and-CSharp-Dynamic-in-Metro-Style-apps.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://jaylee.org/syndication.axd?post=7909136b-8fc7-4e1b-971d-5e23bd2f8562</wfw:commentRss>
    </item>
  </channel>
</rss>