<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US"><title type="html">I know the answer (it's 42)</title><subtitle type="html">A blog on coding, .NET, .NET Compact Framework and life in general....</subtitle><id>http://blogs.msdn.com/abhinaba/atom.xml</id><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/default.aspx" /><link rel="self" type="application/atom+xml" href="http://blogs.msdn.com/abhinaba/atom.xml" /><generator uri="http://communityserver.org" version="2.1.61025.2">Community Server</generator><updated>2009-03-31T10:42:00Z</updated><entry><title>Global variables are bad</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/09/11/global-variables-are-bad.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/09/11/global-variables-are-bad.aspx</id><published>2009-09-11T07:42:00Z</published><updated>2009-09-11T07:42:00Z</updated><content type="html">&lt;a title="Hyderabad Zoological Park by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3675501552/"&gt;&lt;img alt="Hyderabad Zoological Park" src="http://farm3.static.flickr.com/2522/3675501552_494d6ba11b.jpg" width="500" height="457" /&gt;&lt;/a&gt;   &lt;p&gt;&lt;strong&gt;&amp;lt;This post is about C++ (C# folks are saved from this pain)&amp;gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;One of our devs taking care of NETCF on Nokia S60 reported that after the latest code reached their branch things are working very slow. It was observed that Garbage Collector is getting kicked in way more than it should. Investigation showed something interesting.&lt;/p&gt;  &lt;p&gt;I added a global var gcConfig which had a fairly complex constructor and that among other things sets the various member variables like the GC trigger threshold to default value (1mb). All of these works fine on Windows variants.&lt;/p&gt;  &lt;p&gt;However, &lt;a href="http://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language"&gt;TCPL&lt;/a&gt; states “&lt;i&gt;It is generally best to minimize the use of global variables and in particular to &lt;u&gt;limit the use of global variables requiring complicated initialization&lt;/u&gt;.&lt;/i&gt;”. This is especially true for dlls. We tend to ignore good advice sometimes :)&lt;/p&gt;  &lt;p&gt;For Symbian OS (S60) &lt;u&gt;on device&lt;/u&gt; complex ctors of global objects are not run (without any warning). The members are all set to 0 (default member initialization). So in the gcConfig GC-trigger was being set to 0 instead of 1mb. The allocation byte count is compared against this value &lt;a href="http://blogs.msdn.com/abhinaba/archive/2009/03/23/net-compact-framework-gc-quantum.aspx"&gt;to figure out when it’s time to start a GC&lt;/a&gt;. Since it was 0 the collection condition is being met for every allocation and hence for every allocation request GC was being fired!!!&lt;/p&gt;  &lt;p&gt;Actually considering that even after that the app was actually running shows that we have pretty good perf ;)&lt;/p&gt;  &lt;p&gt;A good alternative of using global vars is as follows&lt;/p&gt;  &lt;pre class="Code"&gt;MyClass&amp;amp; useMC()
{
    static MyClass mc; // static ensures objects are not created on each call
    return mc;
}

MyClass&amp;amp; mc = useMC();&lt;/pre&gt;

&lt;p&gt;Do note that this has some multi-threading issue. See &lt;a href="http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx"&gt;http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9893602" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author></entry><entry><title>.NET Compact Framework BCL &lt; .NET BCL</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/09/08/net-compact-framework-bcl-net-bcl.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/09/08/net-compact-framework-bcl-net-bcl.aspx</id><published>2009-09-08T07:42:00Z</published><updated>2009-09-08T07:42:00Z</updated><content type="html">&lt;a title="Hyderabad Zoological Park by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3674684695/"&gt;&lt;img alt="Hyderabad Zoological Park" src="http://farm3.static.flickr.com/2546/3674684695_137c7efb62.jpg" width="500" height="405" /&gt;&lt;/a&gt;   &lt;p&gt;Over twitter some folks are regularly discussing about the fact that there are some chunks of desktop .NET Base class library (BCL) that are missing on the .NET Compact Framework (.NETCF). So I thought I’d post the rationale behind things that are missing and what criteria is used to figure out what makes it in.&lt;/p&gt;  &lt;p&gt;First of all, .NET and .NETCF use completely different runtimes. So the BCL code doesn’t work as is. They need to be ported over. Something being available on the desktop reduces the effort of our BCL team but still significant cost is involved in making it work over NETCF. This means that its not as if everything is available on .NETCF BCL and we cut things out (elimination process), but the other way round where we start from 0 and we need to figure out whether we can take something in. In that process we use some of the following rationale.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;b&gt;ROI:&lt;/b&gt; Does the user scenario that it enables on a mobile device justify the cost      &lt;br /&gt;System.CodeDom.Compiler. Yea right you expected to compile on the phone didn’t you :)       &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Easy workaround available&lt;/b&gt;: If there is an acceptable workaround for a given API then it drops in priority. A trivial example could be that we ship some method overloads but not the other. E.g. Instead of shipping all overloads of Enum.Parse we drop Enum.Parse(Type, String) and keep only Enum.Parse(Type, String, Bool).      &lt;br /&gt;This applies at the level of namespace or Types as well.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Lower in priority list:&lt;/b&gt; It needs work to get it done and it’s lower in priority than other things that is keeping the engineering team busy.       &lt;br /&gt;If there are a lot of request for these features and not good/performant workarounds available then it will go up the priority list and make it to future version of NETCF      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Too large to fit:&lt;/b&gt; Simply too large to fit into our memory limitations      &lt;br /&gt;E.g. Reflection.Emit which leads to other things missing like Dynamic Language Runtime, Linq-to-SQL       &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;No native support:&lt;/b&gt; It uses some underlying OS feature which is either not present on devices or is not relevant to it      &lt;br /&gt;WPF, Parallel computing support&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;With every release developers ask for new features and we also negotiate to increase NETCF footprint budget so that we can include some (but not all) from those requests. To choose what makes it in we use some of the criteria mentioned above.&lt;/p&gt;  &lt;p&gt;Given the system constraints under which NETCF works a vast majority of the desktop APIs will continue to be missing from NETCF. Hopefully this gives you some context behind why those are missing. If you approach NETCF simply from trying to port a desktop application then you would face some frustration on the missing surface area.&lt;/p&gt;  &lt;p&gt;BTW: Do post your comments on this blog or on &lt;a href="http://www.twitter.com"&gt;twitter&lt;/a&gt; (use the #netcf hashtag).&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&amp;lt;Update: I made some updates to this based on feedback /&amp;gt;&lt;/strong&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9892391" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author></entry><entry><title>NETCF: GC and thread blocking</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/09/02/netcf-gc-and-thread-blocking.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/09/02/netcf-gc-and-thread-blocking.aspx</id><published>2009-09-02T07:42:00Z</published><updated>2009-09-02T07:42:00Z</updated><content type="html">&lt;a title="Hyderabad Zoological Park by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3674696765/"&gt;&lt;img alt="Hyderabad Zoological Park" src="http://farm3.static.flickr.com/2579/3674696765_49605f192a.jpg" width="500" height="375" /&gt;&lt;/a&gt;   &lt;p&gt;One of our customers asked us a bunch of questions on the NETCF garbage collector that qualifies as FAQ and hence I thought I’d put them up here.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Question: What is the priority of the GC thread&lt;/strong&gt;     &lt;br /&gt;&lt;strong&gt;Answer: &lt;/strong&gt;Unlike some variants of the desktop GC and other virtual machines (e.g. JScript) we do not have any background or timer based GC. The CLR fires GC on the same thread that tried allocation and either the allocation failed or during pre-allocation checks the CLR feels that &lt;a href="http://blogs.msdn.com/abhinaba/archive/2008/04/29/when-does-the-net-compact-framework-garbage-collector-run.aspx"&gt;time to run GC has come&lt;/a&gt;. So the priority of the GC thread is same as that of the thread that resulted in GC.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Question: Can the GC freeze managed threads that are of higher priority than the GC thread?&lt;/strong&gt;     &lt;br /&gt;&lt;strong&gt;Answer:&lt;/strong&gt; Yes GC can freeze managed threads which has higher priority than itself. Before actually running GC the CLR tries to go into a “safe point”. Each thread has a suspend event associated with it and this event is checked by each thread regularly. Before starting GC the CLR enumerates all managed threads and in each of them sets this event. In the next point when the thread checks and finds this event set, it blocks waiting for the event to get reset (which happens when GC is complete). This mechanism is agnostic of the relative priority of the various threads.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Question: Does it freeze &lt;u&gt;all&lt;/u&gt; threads or only Managed threads?&lt;/strong&gt;     &lt;br /&gt;&lt;strong&gt;Answer:&lt;/strong&gt; The NETCF GC belongs to the category “stop-the-world GC”. It needs to freeze threads so that when it is iterating and compacting managed heap nothing on it gets modified. This is unlike some background/incremental GC supported by other virtual machines.&lt;/p&gt;  &lt;p&gt;GC freezes only managed threads and not other native threads (e.g. COM or host-threads). However, there are two exclusions even on the managed threads&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;It doesn’t freeze the managed thread that started GC because the GC will be run on that thread (see answer to first question) &lt;/li&gt;    &lt;li&gt;Managed threads that are currently executing in native p/invoke code is not frozen either. However, the moment they try to return to managed execution they get frozen. (I actually missed this subtle point in my response and Brian caught it :)) &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Hope this answers some of your questions. &lt;strong&gt;Feel free to send me any .NET Compact Framework CLR questions. I will either answer them myself or get someone else to do it for you :)&lt;/strong&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9889722" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>I am the Empire</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/08/30/i-am-the-empire.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/08/30/i-am-the-empire.aspx</id><published>2009-08-30T07:42:00Z</published><updated>2009-08-30T07:42:00Z</updated><content type="html">&lt;p&gt;&lt;a title="NH5 to Vizag by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/2071230457/"&gt;&lt;img alt="NH5 to Vizag" src="http://farm3.static.flickr.com/2262/2071230457_dc14364c48.jpg" width="500" height="375" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;5 years back exactly on this very day I walked into Cyber Towers office of Microsoft India for the first time. If someone asked me at that time how long I plan to work for Microsoft, my answer would’ve been couple of years max. I was still a bit suspicious of the evil empire and it took some time for me to realize that “I am the empire”. The 5 years has been a mind blowing journey. &lt;/p&gt;  &lt;p&gt;Even though in our industry working for any company for a 5 year stretch is a huge thing, it doesn’t seem so in Microsoft. Our team has 4 people over 20 years and at least 8 people over 10 years. &lt;/p&gt;  &lt;p&gt;Some random thoughts on the last 5 years&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Made my family relocate 3 cities before settling down in Hyderabad (my wife’s threat that the next relocation would be without her helped).&lt;/li&gt;    &lt;li&gt;Bought an apartment &lt;/li&gt;    &lt;li&gt;I have a daughter now who was born around 3 months after I joined MS.&lt;/li&gt;    &lt;li&gt;Started working in a shared office with Ankur and then worked in various cubicles. Finally I have an office.&lt;/li&gt;    &lt;li&gt;3 job designations. SDE to SDEII to Senior SDE. I am fiercely protecting the SDE suffix. &lt;/li&gt;    &lt;li&gt;It’s fantastic to walk into a book store and see books on your work and see screenshots of UI you’ve designed or description of algorithms you’ve come up with.&lt;/li&gt;    &lt;li&gt;327 blog posts on blogs.msdn.com &lt;/li&gt;    &lt;li&gt;I still do not use Visual Studio to edit code&lt;/li&gt;    &lt;li&gt;Finally gave up on Linux even at home. Bye bye Ubuntu, welcome Windows 7&lt;/li&gt;    &lt;li&gt;I have 3 Xboxes in my office and none at home&lt;/li&gt;    &lt;li&gt;I use Nokia phones&lt;/li&gt;    &lt;li&gt;Made fantastic friends at work and sadly few of them are left with Microsoft India (either moved to Redmond or have left MS). Hello Amit, Srivatsn, Ankur :)&lt;/li&gt;    &lt;li&gt;Always wanted to attend a BillG project review but he quit&lt;/li&gt;    &lt;li&gt;Got into some email wars&lt;/li&gt;    &lt;li&gt;I am no longer the fire-head I used to be. I actually think before I speak.&lt;/li&gt;    &lt;li&gt;Went top down from n-tier architectures (TFS), desktop applications (VSTT) and now embedded (NETCF)&lt;/li&gt;    &lt;li&gt;I prefer Starbucks coffee now instead of Darjeeling tea&lt;/li&gt; &lt;/ol&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9888947" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="Everything else" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Everything+else/default.aspx" /><category term="Fun" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Fun/default.aspx" /></entry><entry><title>How does the .NET Compact Memory allocator work</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/06/01/how-does-the-net-compact-memory-allocator-work.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/06/01/how-does-the-net-compact-memory-allocator-work.aspx</id><published>2009-06-01T07:42:00Z</published><updated>2009-06-01T07:42:00Z</updated><content type="html">&lt;a title="Aalankrita - Twins by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3559720765/"&gt;&lt;img height="400" alt="Aalankrita - Twins" src="http://farm4.static.flickr.com/3661/3559720765_cec30e5a74.jpg" width="500" /&gt;&lt;/a&gt;   &lt;p&gt;As I mentioned in one of my &lt;a href="http://blogs.msdn.com/abhinaba/archive/2009/03/30/how-many-heaps-does-the-net-compact-framework-use.aspx"&gt;previous posts&lt;/a&gt; the .NET Compact Framework uses 5 separate heaps of which one is dedicated for managed data and is called the managed heap. The .NETCF allocator, allocates pools of data from this managed heap and then sub-allocates managed objects from this pool.&lt;/p&gt;  &lt;p&gt;This is how the process goes&lt;/p&gt;  &lt;table cellspacing="0" cellpadding="2" width="680" border="0"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="200"&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_4.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="232" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_1.png" width="197" border="0" /&gt;&lt;/a&gt; &lt;/td&gt;        &lt;td valign="top" width="478"&gt;At the very beginning the allocator allocates a 64Kb pool (called the obj-pool) and ties it with the current app-domain state (AppState).&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="200"&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_6.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_2.png" width="224" border="0" /&gt;&lt;/a&gt; &lt;/td&gt;        &lt;td valign="top" width="478"&gt;All object allocation requests are served from this pool (Pool 0). After each allocation an internal pointer (shown in yellow) is incremented to point to the end of the last allocated object.&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="200"&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_8.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_3.png" width="209" border="0" /&gt;&lt;/a&gt; &lt;/td&gt;        &lt;td valign="top" width="478"&gt;Subsequent allocation is just incrementing this pointer.&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="200"&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_10.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_4.png" width="202" border="0" /&gt;&lt;/a&gt; &lt;/td&gt;        &lt;td valign="top" width="478"&gt;This goes on until the point where there is no more space left in the current obj-pool&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="200"&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_14.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="259" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_6.png" width="320" border="0" /&gt;&lt;/a&gt; &lt;/td&gt;        &lt;td valign="top" width="478"&gt;Since there is no more space left in the current pool (pool 0) a new pool (pool 1) is allocated and all subsequent object allocation requests are serviced from the new pool.&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;The first question I get asked at this point is what happens when one object itself is bigger than 64Kb :). The answer is that the CLR considers such objects as “huge-objects” and they are placed in their own obj-pool. This essentially means that either obj-pools are 64Kb in size and has more than one object in them or are bigger than 64Kb and has only one huge-object in it.&lt;/p&gt;  &lt;p&gt;Object allocation speed varies a lot between whether it is being allocated from the current pool (where it is just the cost of a pointer increment) or it needs a new pool to be allocated (where there is additional cost of a 64Kb allocation). On the average managed objects are 35 bytes in size and around 1800 can fit in one pool and hence on the whole allocation speed attained is pretty good.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Verifying what we discussed above&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;All of the things I said above can be easily verified using the Remote Performance monitor. I wrote a small application that allocates objects in a loop and launched it under Remote Performance monitor and published the data to perfmon so that I can observe how the managed heap grows. I used the process outlined in Steven Pratschner’s blog post at &lt;a title="http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx" href="http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx"&gt;http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_16.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="683" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/Howdoesthe.NETCompactMemoryallocatorwork_F51E/image_thumb_7.png" width="741" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Using the above mentioned mechanism I am observing the managed bytes allocated (green line) and the GC Heap (red line). You can see that the green line increases linearly and after every 64Kb the red line or the GC Heap bumps up by 64Kb as we allocate a new object pool from the heap.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9669293" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>Memory leak via event handlers</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/05/05/memory-leak-via-event-handlers.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/05/05/memory-leak-via-event-handlers.aspx</id><published>2009-05-05T07:42:00Z</published><updated>2009-05-05T07:42:00Z</updated><content type="html">&lt;a title="Golconda fort - light and sound by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/478223125/"&gt;&lt;img alt="Golconda fort - light and sound" src="http://farm1.static.flickr.com/190/478223125_9884251249.jpg" width="500" height="301" /&gt;&lt;/a&gt;   &lt;p&gt;One of our customers recently had some interesting out-of-memory issues which I thought I’d share.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The short version&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The basic problem was that they had event sinks and sources. The event sinks were disposed correctly. However, in the dispose they missed removing the event sink from the event invoker list of the source. So in effect the disposed sinks were still reachable from the event source which is still in use. So GC did not de-allocate the event sinks and lead to leaked objects.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Now the not-so-long version&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Consider the following code where there are EventSource and EventSink objects. EventSource exposes the event SomeEvent which the sink listens to.&lt;/p&gt;  &lt;pre class="code"&gt;EventSink sink = new EventSink();
EventSource src = new EventSource();

src.SomeEvent += sink.EventHandler;
src.DoWork();

&lt;font color="#ff5555"&gt;sink = null;&lt;/font&gt;
&lt;font color="#00ce00"&gt;// Force collection&lt;/font&gt;
GC.Collect();
GC.WaitForPendingFinalizers();&lt;/pre&gt;

&lt;p&gt;For the above code if you have a finalizer for EventSink and add a breakpoint/Console.WriteLine in it, you’d see that it is never hit even though sink is clearly set to null. The reason is the 3rd line where we added sink to the invoke list of source via the += operator. So even after sink being set to null the original object is still reachable (and hence not garbage) from src.&lt;/p&gt;

&lt;p&gt;+= is additive so as the code executes and new sinks are added the older objects still stick around resulting in working set to grow and finally lead to crash at some point.&lt;/p&gt;

&lt;p&gt;The fix is to ensure you remove the sink with –= as in&lt;/p&gt;

&lt;pre class="code"&gt;EventSink sink = new EventSink();
EventSource src = new EventSource();
src.SomeEvent += sink.EventHandler;
src.DoWork();
&lt;font color="#00e600"&gt;src.SomeEvent -= sink.EventHandler;&lt;/font&gt;
sink = null;&lt;/pre&gt;

&lt;p&gt;The above code is just sample and obviously you shouldn’t do event add removal in a scattered way. Make EventSink implement IDisposable and encapsulate the += –= in ctor/dispose.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9586032" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>Finalizers and Thread local storage</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/29/finalizers-and-thread-local-storage.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/29/finalizers-and-thread-local-storage.aspx</id><published>2009-04-29T07:42:00Z</published><updated>2009-04-29T07:42:00Z</updated><content type="html">&lt;a title="Sunset from our balcony by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/535766822/"&gt;&lt;img alt="Sunset from our balcony" src="http://farm1.static.flickr.com/213/535766822_618635ea29.jpg" width="500" height="375" /&gt;&lt;/a&gt;   &lt;p&gt;Writing finalizers is generally tricky. In the &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx"&gt;msdn documentation for finalizers&lt;/a&gt; the following limitations are mentioned.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The exact time when the finalizer executes during garbage collection is undefined &lt;/li&gt;    &lt;li&gt;The finalizers of two objects are not guaranteed to run in any specific order &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;The thread on which the finalizer is run is unspecified. &lt;/strong&gt;&lt;/li&gt;    &lt;li&gt;Finalizers might not be run at all &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;#3 has interesting consequences. If a native resources is allocated by a managed ctor (or any other method) and the finalizers is used to de-allocate that then the allocation and de-allocation will not happen on the same thread. The reason being that the CLR uses one (maybe more than one) special thread to run all finalizers on. This is easily verified by the fact that if you query for the thread id inside the finalizers you will get a different id than the main thread the application is being run on.&lt;/p&gt;  &lt;p&gt;The thread safety is generally easy to handle but might lead to some tricky and hard to locate problems. Consider the following code&lt;/p&gt;  &lt;pre class="code"&gt;class MyClass
{
    public MyClass()
    {
        tls = 42;
        Console.WriteLine(&amp;quot;Ctor threadid = {0} TLS={1}&amp;quot;, AppDomain.GetCurrentThreadId(), &lt;font color="#00d5d5"&gt;tls&lt;/font&gt;);
    }

    ~MyClass()
    {
        Console.WriteLine(&amp;quot;Finalizer threadid = {0} TLS={1}&amp;quot;, AppDomain.GetCurrentThreadId(), &lt;font color="#00d5d5"&gt;tls&lt;/font&gt;);
    }

    public void DoWork()
    {
        Console.WriteLine(&amp;quot;DoWork threadid = {0} TLS={1}&amp;quot;, AppDomain.GetCurrentThreadId(), &lt;font color="#00d5d5"&gt;tls&lt;/font&gt;);
    }

    &lt;font color="#00caca"&gt;[ThreadStatic]&lt;/font&gt;
    static int tls;
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        mc.DoWork();
        mc = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}&lt;/pre&gt;

&lt;p&gt;Here we create a class, use it and finalize it. In all of these 3 methods we print the thread id and also use a special variable named tls.&lt;/p&gt;

&lt;p&gt;If you see the tls is marked with the attribute &lt;a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(vs.71).aspx"&gt;ThreadStatic&lt;/a&gt;. The definition of ThreadStatic is “&lt;em&gt;Indicates that the value of a static field is unique for each thread&lt;/em&gt;”. &lt;/p&gt;

&lt;p&gt;I hope by now you have figured out the gotcha :). Under the hood the CLR uses a native OS concept called &lt;a href="http://msdn.microsoft.com/en-us/library/ms686749.aspx"&gt;Thread Local Usage&lt;/a&gt; (TLS) to ensure that the value of tls is unique per thread. TLS uses special per thread data-structure to store that data. Now we have set the value in the ctor and used it in finalizer. Since they run on different threads each will get different values of the same field.&lt;/p&gt;

&lt;p&gt;On my system the out put is as follows&lt;/p&gt;

&lt;pre class="Console"&gt;Ctor threadid = 5904 TLS=42
DoWork threadid = 5904 TLS=42
Finalizer threadid = &lt;font color="#ff6464"&gt;4220 TLS=0&lt;/font&gt;
Press any key to continue . . .&lt;/pre&gt;

&lt;p&gt;As is evident the finalizer ran on a different thread (id is different) and the TLS value is also different from what was set.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So the moral of this story is “&lt;em&gt;Be careful about thread safety of finalizers and do not use thread local storage in it&lt;/em&gt;”&lt;/strong&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9573776" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>What post are you known for?</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/20/what-post-are-you-known-for.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/20/what-post-are-you-known-for.aspx</id><published>2009-04-20T07:42:00Z</published><updated>2009-04-20T07:42:00Z</updated><content type="html">&lt;a title="Charminar, Hyderabad by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3305852537/"&gt;&lt;img alt="Charminar, Hyderabad" src="http://farm4.static.flickr.com/3622/3305852537_76499bfb68.jpg" width="375" height="500" /&gt;&lt;/a&gt;   &lt;p&gt;I was just listening to &lt;a href="http://www.hanselman.com/blog/HanselminutesPodcast158SecretsOfFogCreekWithJoelSpolsky.aspx"&gt;Scot Hanselman’s podcast&lt;/a&gt; where he interviews Joel. They talk about how most bloggers get known for one post. E.g. Joel is known for “&lt;a href="http://www.joelonsoftware.com/articles/Unicode.html"&gt;The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)&lt;/a&gt;”.&lt;/p&gt;  &lt;p&gt;Now obviously I’m not a famous blogger and I’m not known for any post but the fact that my most read post is “&lt;a href="http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx"&gt;How many (.NET) types are loaded for Hello World&lt;/a&gt;” makes me feel a bit weird. IMO that is one of the least useful posts I’ve ever written.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9555004" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="Everything else" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Everything+else/default.aspx" /></entry><entry><title>.NET Code Pitching</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/17/net-code-pitching.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/17/net-code-pitching.aspx</id><published>2009-04-17T07:42:00Z</published><updated>2009-04-17T07:42:00Z</updated><content type="html">&lt;a title="Raiding dads office by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3436132492/"&gt;&lt;img alt="Raiding dads office" src="http://farm4.static.flickr.com/3343/3436132492_be347bdbb2.jpg" width="500" height="419" /&gt;&lt;/a&gt;   &lt;p&gt;The word pitch can have many meanings, but in case of the code pitching it is used in the sense of “to throw away”.&lt;/p&gt;  &lt;p&gt;The desktop CLR never throws away or pitches native code that it JITs. However, the .NET Compact Framework CLR supports code pitching due to the following reasons&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;It is targeted towards embedded/mobile systems and therefore needs to be more sensitive towards memory usage. So in some situations it throws away JITed code to free up memory. &lt;/li&gt;    &lt;li&gt;NETCF runs on RISC processors like ARM where code density is lower than that of x86. This means the JITed native code is larger in size for a given set of IL on say ARM vs that on say x86. Due to this the memory usage overhead is a bit aggravated. However, this isn’t really a primary motivator and there are other work around like using the newer ARM instruction set extensions.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Code pitching can happen due to various reasons like (note this is not an exhaustive list)&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;When the managed application gets WM_HIBERNATE message it fires a round of garbage collection and also pitches code&lt;/li&gt;    &lt;li&gt;When the JITer fails to allocate memory it attempts code pitching to free up memory and re-tries allocation&lt;/li&gt;    &lt;li&gt;Other native resource allocation failures also initiates pitching &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Obviously code pitching has performance implications and can result in the same method being pitched multiple times. You can monitor code pitching in Remote Performance Monitor.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/CodePitching_12558/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/abhinaba/WindowsLiveWriter/CodePitching_12558/image_thumb.png" width="815" height="613" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;As the name suggests the GC does drive code pitching but they are not essentially related. E.g. if user code forces GC by &lt;a href="http://msdn.microsoft.com/en-us/library/xe0c2357.aspx"&gt;System.GC.Collect()&lt;/a&gt; code pitching is not done. Code pitching is primarily driven by real low memory scenarios.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Caveat: &lt;/strong&gt;While pitching the CLR ensures that it doesn’t throw away any JITed method on the current managed execution stack. No points for guessing why that is important.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9553125" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>Multiple calls to GC.ReRegisterForFinalize</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/15/multiple-calls-to-gc-reregisterforfinalize.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/15/multiple-calls-to-gc-reregisterforfinalize.aspx</id><published>2009-04-15T07:42:00Z</published><updated>2009-04-15T07:42:00Z</updated><content type="html">&lt;a title="Holi Celebration at our appartment complex by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3346305361/"&gt;&lt;img alt="Holi Celebration at our appartment complex" src="http://farm4.static.flickr.com/3595/3346305361_89912328e9.jpg" width="500" height="364" /&gt;&lt;/a&gt;   &lt;p&gt;What happens when there are multiple calls to &lt;a href="http://msdn.microsoft.com/en-us/library/system.gc.reregisterforfinalize.aspx"&gt;GC.ReRegisterForFinalize&lt;/a&gt; for the same object? &lt;/p&gt;  &lt;p&gt;Consider the following C# code&lt;/p&gt;  &lt;pre class="code"&gt;class MyClass
{
    ~MyClass()
    {
        Console.WriteLine(&amp;quot;~MyClass&amp;quot;);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        GC.ReRegisterForFinalize(mc); &lt;font color="#00cc66"&gt;// 1&lt;/font&gt;
        GC.ReRegisterForFinalize(mc); &lt;font color="#00cc66"&gt;// 2&lt;/font&gt;
        GC.ReRegisterForFinalize(mc); &lt;font color="#00cc66"&gt;// 3&lt;/font&gt;

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}&lt;/pre&gt;

&lt;p&gt;Here for the same object we have called GC.ReRegisterForFinalize thrice. &lt;/p&gt;

&lt;p&gt;This is one of the few cases where the behavior of &lt;em&gt;.NET &lt;/em&gt;and &lt;em&gt;.NET Compact Framework&lt;/em&gt; differs.&lt;/p&gt;

&lt;p&gt;In case of .NET the MyClass finalizer is called 4 times. Since the object has a finalizer, it is anyway finalized once and for the additional 3 calls to re-register it is finalized 3 more times.&lt;/p&gt;

&lt;p&gt;In case of .NET Compact Framework the finalizer is called only once. The reason being internally finalizable is just a bool flag. Each time &lt;a href="http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx"&gt;GC.SuppressFinalize&lt;/a&gt; is called it is set to false and each time GC.ReRegisterForFinalize is called it is set to true. So multiple calls doesn’t have any effect.&lt;/p&gt;

&lt;p&gt;Hopefully this is one piece of information which none of my readers ever find useful, but since I got a bug assigned for the difference in behavior I might as well let folks know.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9544192" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry><entry><title>.NET Compact Framework MemMaker</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/14/net-compact-framework-memmaker.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/14/net-compact-framework-memmaker.aspx</id><published>2009-04-14T07:42:00Z</published><updated>2009-04-14T07:42:00Z</updated><content type="html">&lt;A title="2007_01_28 120 by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/376344278/" mce_href="http://www.flickr.com/photos/abhinaba/376344278/"&gt;&lt;IMG alt="2007_01_28 120" src="http://farm1.static.flickr.com/184/376344278_e1c1537d93.jpg" width=500 height=433 mce_src="http://farm1.static.flickr.com/184/376344278_e1c1537d93.jpg"&gt;&lt;/A&gt; 
&lt;BLOCKQUOTE&gt;“&lt;EM&gt;Glen recently discovered that by keeping his application’s EXE empty and putting all the forms, code, resources, and data in managed DLLs, he reduced the amount of virtual memory his app uses inside its slot while at the same time taking advantage of memory outside the slot in the 1 GB shared memory area&lt;/EM&gt;”&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Read more about this very interesting finding at Rob Tiffany’s blog at &lt;A title=http://blogs.msdn.com/robtiffany/archive/2009/04/09/memmaker-for-the-net-compact-framework.aspx href="http://blogs.msdn.com/robtiffany/archive/2009/04/09/memmaker-for-the-net-compact-framework.aspx" mce_href="http://blogs.msdn.com/robtiffany/archive/2009/04/09/memmaker-for-the-net-compact-framework.aspx"&gt;http://blogs.msdn.com/robtiffany/archive/2009/04/09/memmaker-for-the-net-compact-framework.aspx&lt;/A&gt;&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9543115" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author></entry><entry><title>Object Resurrection using GC.ReRegisterForFinalize</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/13/object-resurrection-using-gc-reregisterforfinalize.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/13/object-resurrection-using-gc-reregisterforfinalize.aspx</id><published>2009-04-13T07:42:00Z</published><updated>2009-04-13T07:42:00Z</updated><content type="html">&lt;a title="Fireworks by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/377698664/"&gt;&lt;img alt="Fireworks" src="http://farm1.static.flickr.com/138/377698664_7bd0867e94.jpg" width="500" height="375" /&gt;&lt;/a&gt;   &lt;p&gt;I have been thinking about writing this post for some time, but &lt;a href="http://en.wikipedia.org/wiki/Easter"&gt;Easter weekend&lt;/a&gt; provided the right context to do so.&lt;/p&gt;  &lt;p&gt;When I first encountered &lt;a href="http://msdn.microsoft.com/en-us/library/system.gc.reregisterforfinalize.aspx"&gt;GC.ReRegisterForFinalize&lt;/a&gt; I was a bit baffled. The context help “&lt;em&gt;Requests that the system call the finalizer for the specified object for which System.GC.SuppressFinalize(System.Object) has previously been called.&lt;/em&gt;” didn’t provide much clue as to why I would want to finalize an object more than once.&lt;/p&gt;  &lt;p&gt;This is when I found out about object resurrection.&lt;/p&gt;  &lt;blockquote&gt;&lt;em&gt;&lt;b&gt;res·ur·rec·tion&lt;/b&gt;&amp;#160;&amp;#160; (rěz'ə-rěk'shən)       &lt;br /&gt;&lt;strong&gt;-noun&lt;/strong&gt;       &lt;br /&gt;&lt;/em&gt;    &lt;ol&gt;     &lt;li&gt;&lt;em&gt;The act of rising from the dead or returning to life. &lt;/em&gt;&lt;/li&gt;      &lt;li&gt;&lt;em&gt;The state of one who has returned to life. &lt;/em&gt;&lt;/li&gt;      &lt;li&gt;&lt;em&gt;The act of bringing back to practice, notice, or use; revival. &lt;/em&gt;&lt;/li&gt;   &lt;/ol&gt; &lt;/blockquote&gt;  &lt;p&gt;This definition made perfect sense. The basic idea of using object resurrection is to handle scenarios where an object creation is very expensive for some reason (e.g. it makes system calls that take a lot of time or consumes a lot of resources). To avoid creating new objects and incur the creation cost again, you’d try to re-cycle older objects which have already done their job or in other words resurrect dead objects.&lt;/p&gt;  &lt;p&gt;This can be done by using the following facts&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;If an object is garbage (not-reachable) and has a finalizer, it is not collected in the first pass of the GC but is placed in the finalizer queue &lt;/li&gt;    &lt;li&gt;The finalizer thread calls the finalizers of each object in the finalizer queue and removes it from the queue. &lt;/li&gt;    &lt;li&gt;The next pass of the GC actually reclaims the object (as in de-allocate the memory) &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In #2 above when the finalizer is executing if a new reference to the object is created and GC.ReRegisterForFinalize is called then the object becomes reachable and hence non garbage and so in #3 the GC will not reclaim it. Since GC.ReRegisterForFinalize is called, in the next cycle when the same object is available for collection #1 through #3 will again follow (so we set up the cycle).&lt;/p&gt;  &lt;p&gt;Consider the scenario where MyClass is a class which is expensive to create. We want to setup a pool of these objects so that we can just pick up objects from this pool and once the object is done with, it is automatically put into that pool.&lt;/p&gt;  &lt;pre class="code"&gt;class MyClass
{
    &lt;font color="#cdcdcd"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;font color="#06ff83"&gt;Expensive class&lt;/font&gt;
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;pool&amp;quot; /&amp;gt;&lt;font color="#06ff83"&gt;Pool from which the objects are picked up&lt;/font&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;
    public MyClass(List&lt;myclass&gt; pool)
    {
        Console.WriteLine(&lt;font color="#ffa6ff"&gt;&amp;quot;Expensive MyClass::ctor&amp;quot;&lt;/font&gt;);
        this.pool = pool; &lt;font color="#00cc66"&gt;// Store the pool so we can use it later &lt;/font&gt;
    }

    public void DoWork()
    {
        Console.WriteLine(&lt;font color="#ffa6ff"&gt;&amp;quot;{0} Did some work&amp;quot;&lt;/font&gt;, this.resurrectionCount);
    }

    &lt;font color="#bebebe"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;font color="#06ff83"&gt;Finalizer method&lt;/font&gt;
    /// &amp;lt;/summary&amp;gt;&lt;/font&gt;
    ~MyClass()
    {
        resurrectionCount++;
        &lt;font color="#00cc66"&gt;// automatically return to the pool, makes this object reachable as well&lt;/font&gt;
        pool.Add(this); 

        &lt;font color="#00cc66"&gt;// Ensure next time this same finalizer is called again&lt;/font&gt;
        GC.ReRegisterForFinalize(this);
    }

    private List&amp;lt;MyClass&amp;gt; pool;
    private int resurrectionCount = 0;
}

&lt;font color="#00cc66"&gt;// Create pool and add a bunch of these objects to the pool
&lt;/font&gt;List&lt;myclass&gt; pool = new List&lt;myclass&gt;();
pool.Add(new MyClass(pool));
pool.Add(new MyClass(pool));

&lt;font color="#00cc66"&gt;// Client code&lt;/font&gt;
MyClass cl = pool[0]; &lt;font color="#00cc66"&gt;// get the object at the head of the pool&lt;/font&gt;
pool.RemoveAt(0);     &lt;font color="#00cc66"&gt;// remove the object&lt;/font&gt;
cl.DoWork();          &lt;font color="#00cc66"&gt;// start using it. Once done it will automatically go back to pool&lt;/font&gt;&lt;/pre&gt;

&lt;p&gt;At the start a bunch of these objects are created and put in this list of objects (taking a hit in startup time). Then as and when required they are removed from this list and put to work. Once the work is done they automatically get en-queued back to the pool as the finalizer call will ensure that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t do this&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Even though the above mechanism seems pretty tempting, it is actually a very bad idea to really use this method. The major reason being that the CLR never guarantees when GC is run and post that when the finalizer will be run. So in effect even though a bunch of these objects have done their job it will be not be deterministic on when they will land up back in the queue.&lt;/p&gt;

&lt;p&gt;If you really need to use object pooling a much better approach is to implement your special interface where you provide a method which is explicitly called by client code and is therefore deterministically controllable.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9544116" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /></entry><entry><title>Technical Presentation Tip</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/07/technical-presentation-tip.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/07/technical-presentation-tip.aspx</id><published>2009-04-07T07:42:00Z</published><updated>2009-04-07T07:42:00Z</updated><content type="html">&lt;a title="Co-existance by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3415745874/"&gt;&lt;img alt="Co-existance" src="http://farm4.static.flickr.com/3319/3415745874_d96a3c2a12.jpg" width="500" height="381" /&gt;&lt;/a&gt;   &lt;p&gt;I’m no &lt;a href="http://www.hanselman.com/blog/"&gt;Scot Hanselman&lt;/a&gt;, but even then I guess I can share at least one tip for delivering technical presentation that has worked very well for me.&lt;/p&gt;  &lt;p&gt;At the very beginning of your presentation always have a slide clearly calling out what the attendees will “Take Away” and what is the “Pre-requisites'” of attending your presentation. Presentation titles sometime mislead and is generally not enough to indicate what a presentation is all about. &lt;/p&gt;  &lt;p&gt;Benefits of calling out key take-away&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Helps you focus on what you want to convey and you can take feedback from the attendees on whether you met the expectation that you set.&lt;/li&gt;    &lt;li&gt;If an attendee feels he already knows about the topic or is not really interested for some other reason he can leave at the very beginning. No point wasting anyone’s time. &lt;/li&gt;    &lt;li&gt;You can direct discussion/questions. If someone tries venturing into an area you intentionally don’t want to cover you can get the discussion onto the right track. When I give my GC Theory talk I call out very clearly that the presentation is not about how either .NET or .NETCF implements GC and inevitably when someone ventures into some .NET implementation detail and I use this to get back to the main course. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Benefits of calling out pre-requisite&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Just like you need to ensure you are not wasting the attendees time by calling out take aways, you should ensure that you are not wasting your time trying to explain garbage collection to device driver programmers :) &lt;/li&gt;    &lt;li&gt;Explaining basic stuff to one attendee (who raises them) and wasting the time of all other attendees who already know the answer is not a good use of anyone’s time. _ASSERT on the pre-reqs and ensure that you are clear about what baseline knowledge you are expecting out of all the attendees. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;You can learn more real presentation tips from Scot’s &lt;a href="http://www.hanselman.com/blog/11TopTipsForASuccessfulTechnicalPresentation.aspx"&gt;post&lt;/a&gt; and maybe then one day you’ll earn a feedback comment “&lt;em&gt;The presentation was superb. I think this is the first presentation for which I was completely awake&lt;/em&gt;” and try to figure out who that one was ;)&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9532359" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="Everything else" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Everything+else/default.aspx" /><category term="Fun" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Fun/default.aspx" /><category term="Tech" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Tech/default.aspx" /><category term="Software" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Software/default.aspx" /><category term="Technology" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Technology/default.aspx" /></entry><entry><title>Floating point operations in .NET Compact Framework on WinCE+ARM</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/04/06/floating-point-operations-in-net-compact-framework-on-wince-arm.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/04/06/floating-point-operations-in-net-compact-framework-on-wince-arm.aspx</id><published>2009-04-06T07:42:00Z</published><updated>2009-04-06T07:42:00Z</updated><content type="html">&lt;a title="Holi Celebration at our appartment complex by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3346297307/"&gt;&lt;img alt="Holi Celebration at our appartment complex" src="http://farm4.static.flickr.com/3550/3346297307_440d2fd740.jpg" width="500" height="375" /&gt;&lt;/a&gt;   &lt;p&gt;There has been a some confusion on how .NETCF handles floating point operations. The major reason for this confusion is due to the fact that the answer differs across the platforms NETCF supports (e.g. S60/Xbox/Zune/WinCE). I made a &lt;a href="http://blogs.msdn.com/abhinaba/archive/2009/03/27/net-compact-framework-and-arm-fpu.aspx"&gt;post&lt;/a&gt; on this topic which is partially incorrect. As I followed that up I learnt a lot, especially from &lt;strong&gt;Brian Smith&lt;/strong&gt;. Hopefully this post removes all the confusions floating around floating point handling in .NETCF on WinCE.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;How does desktop CLR handle floating point operation&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Consider the following floating point addition in C#&lt;/p&gt;  &lt;pre class="code"&gt;float a = 0.7F;
float b = 0.6F;
float c = a + b;&lt;/pre&gt;

&lt;p&gt;For this code the final assembly generated by CLR JITer on x86 platform is&lt;/p&gt;

&lt;pre&gt;           &lt;strong&gt; float a = 0.7F;&lt;/strong&gt;
&lt;font color="#808080"&gt;0000003f  mov         dword ptr [ebp-40h],3F333333h&lt;/font&gt; 
            &lt;strong&gt;float b = 0.6F;&lt;/strong&gt;
&lt;font color="#808080"&gt;00000046  mov         dword ptr [ebp-44h],3F19999Ah&lt;/font&gt; 
            &lt;strong&gt;float c = a + b;&lt;/strong&gt;
&lt;font color="#949494"&gt;0000004d  &lt;font color="#ff0000"&gt;fld&lt;/font&gt;         dword ptr [ebp-40h] 
00000050  &lt;font color="#ff0000"&gt;fadd&lt;/font&gt;        dword ptr [ebp-44h] 
00000053  &lt;font color="#ff0000"&gt;fstp&lt;/font&gt;        dword ptr [ebp-48h]&lt;/font&gt; &lt;/pre&gt;

&lt;p&gt;Here the JITter directly emits floating point instructions fld, fadd and fstp. It could do so because floating point unit and hence the floating point instructions are always available on x86.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does NETCF differ&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately NETCF targets a huge number of HW configs which vary across Xbox, Zune, WinCE on x86/MIPS/ARM/SH4, S60, etc.&amp;#160; There are even sub-flavors of these base configs (e.g. ARMv4, ARMv6, MIPS II, MIPS IV). On all of these platforms floating point unit (FPU) is not available.&lt;/p&gt;

&lt;p&gt;This difference in FPU availability is taken care of by using different approaches on different platforms. This post is for WinCE+ARM and hence I’ll skip the other platforms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Zune in a special WinCE platform&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Zune is special because it is tied to a specific version of ARM with FPU built in (locked HW). NETCF on Zune was primarily targeted for XNA games and on games performance of floating point operation is critical. Hence the .NETCF JITer was updated to target ARM FPU. So for basic mathematical operation it emits inline native ARM FPU instructions very much like the desktop JITter shown above. The result is that the basic floating point operations are much faster.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WinCE in general&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In general for WinCE on ARM, presence of FPU cannot be assumed because the least common subset targeted is ARMv4 which doesn’t essentially have a FPU. &lt;/p&gt;

&lt;p&gt;To understand the implication it is important to understand that floating point operations can be basically classified into two categories:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;BCL System.Math operations like sin/cos/tan &lt;/li&gt;

  &lt;li&gt;Simple floating point operations like +,/,- , *, conversion, comparison. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For the first category the JITer simply delegates the operation into WinCE by calling into &lt;a href="http://blogs.gotdotnet.com/ce_base/archive/2006/02/02/Inside-Windows-CE-API-Calls.aspx"&gt;CoreDll.dll&lt;/a&gt;, e.g. the sin, sinh, cos, cosh, etc.. available in CoreDll.dll.&lt;/p&gt;

&lt;p&gt;For the second category the JITer calls into small worker functions implemented inside the NETCF CLR. These worker functions are native code and compiled for ARM. If we disassemble them we would see that for these the native ARM compiler emits calls into coredll.dll into say __imp___addd&lt;/p&gt;

&lt;p&gt;It is evident from above that the performance of managed floating point operation is heavily dependent on whether the underlying WinCE uses the ARM FPU as in most scenarios floating point operations are finally delegated into it. &lt;/p&gt;

&lt;p&gt;The whole thing can be summarized in the following table (courtesy Brian Smith)&lt;/p&gt;

&lt;table border="0" cellspacing="0" cellpadding="0"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign="top" width="213"&gt;&lt;/td&gt;

      &lt;td bgcolor="#4f6228" valign="top" width="426" colspan="2"&gt;
        &lt;p align="center"&gt;&lt;b&gt;&lt;font color="#ffffff"&gt;WinCE6 + ARMv4i&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;
      &lt;/td&gt;

      &lt;td bgcolor="#4f6228" valign="top" width="297"&gt;
        &lt;p align="center"&gt;&lt;b&gt;&lt;font color="#ffffff"&gt;WinCE6 + ARMv6_FP&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;
      &lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="213"&gt;&lt;/td&gt;

      &lt;td bgcolor="#76923c" valign="top" width="213"&gt;
        &lt;p align="center"&gt;&lt;b&gt;&lt;u&gt;#1&lt;/u&gt; CE is NOT FPU optimized&lt;/b&gt;&lt;/p&gt;
      &lt;/td&gt;

      &lt;td bgcolor="#76923c" valign="top" width="213"&gt;
        &lt;p align="center"&gt;&lt;b&gt;&lt;u&gt;#2&lt;/u&gt; CE is FPU optimized&lt;/b&gt;&lt;/p&gt;
      &lt;/td&gt;

      &lt;td bgcolor="#76923c" valign="top" width="297"&gt;
        &lt;p align="center"&gt;&lt;b&gt;&lt;u&gt;#3&lt;/u&gt; CE is FPU optimized and so is NETCF (e.g. Zune JIT)&lt;/b&gt;&lt;/p&gt;
      &lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td bgcolor="#76923c" valign="top" width="213"&gt;
        &lt;p&gt;&lt;strong&gt;System.Math library calls&lt;/strong&gt;&lt;/p&gt;
      &lt;/td&gt;

      &lt;td valign="top" width="213"&gt;
        &lt;p&gt;Delegated via pinvoke, emulated within CE (speed: &lt;strong&gt;slow&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;

      &lt;td bgcolor="#f2dbdb" valign="top" width="213"&gt;
        &lt;p&gt;Delegated via pinvoke, FPU instructions within CE (speed: &lt;strong&gt;medium&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;

      &lt;td valign="top" width="297"&gt;
        &lt;p&gt;Delegated via pinvoke, FPU instructions within CE (speed: &lt;strong&gt;medium&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td bgcolor="#76923c" valign="top" width="213"&gt;
        &lt;p&gt;&lt;strong&gt;FP IL opcodes (add, etc)&lt;/strong&gt;&lt;/p&gt;
      &lt;/td&gt;

      &lt;td valign="top" width="213"&gt;
        &lt;p&gt;Delegated via JIT worker, emulated within CE (speed: &lt;strong&gt;slow&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;

      &lt;td bgcolor="#f2dbdb" valign="top" width="213"&gt;
        &lt;p&gt;Delegated via JIT worker, FPU instructions within CE (speed: &lt;strong&gt;medium&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;

      &lt;td valign="top" width="297"&gt;
        &lt;p&gt;FPU instructions inlined by JITed code (speed: &lt;strong&gt;fast&lt;/strong&gt;)&lt;/p&gt;
      &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;#1 is the general case for NETCF + WinCE + ARM. #3 is the current scenario of NETCF + Zune + ARM.&lt;/p&gt;

&lt;p&gt;#2 is based on the fact that WinCE 6.0 supports “pluggable” FP library. However, the NETCF team has not tried out this flavor and hence does not give any guidance on whether plugging in a FP library in WinCE will really have any performance improvement, however theoretically it does seems likely.&lt;/p&gt;

&lt;p&gt;#3 today is only for Zune, but going forward it does seem likely that newer versions of WinCE will update it’s base supported HW spec, it will include FPU and then this feature will also make it to base NETCF for WinCE.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9531381" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Software" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Software/default.aspx" /></entry><entry><title>NETCF: Total Bytes in Use After GC – Perf counter</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/abhinaba/archive/2009/03/31/netcf-total-bytes-in-use-after-gc-perf-counter.aspx" /><id>http://blogs.msdn.com/abhinaba/archive/2009/03/31/netcf-total-bytes-in-use-after-gc-perf-counter.aspx</id><published>2009-03-31T07:42:00Z</published><updated>2009-03-31T07:42:00Z</updated><content type="html">&lt;a title="Holi Celebration at our appartment complex by abhinaba, on Flickr" href="http://www.flickr.com/photos/abhinaba/3347129858/"&gt;&lt;img alt="Holi (The festival of colors) celebration in full swing" src="http://farm4.static.flickr.com/3639/3347129858_9538563194.jpg" width="500" height="412" /&gt;&lt;/a&gt;   &lt;p&gt;At least one of our customers were a bit confused with the &lt;a href="http://msdn.microsoft.com/en-us/library/ms172525.aspx#gc"&gt;.NET Compact Framework performance counter&lt;/a&gt; “Total Bytes in Use After GC” which is described as “&lt;em&gt;The number of bytes of memory, native and managed, in use after the last garbage collection.&lt;/em&gt;”. The description lead him to believe it is the total memory in use by a given managed application. That is not true.&lt;/p&gt;  &lt;p&gt;The memory inside a .NET Compact Framework managed application can be broadly classified into &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Managed memory &lt;/li&gt;    &lt;li&gt;Jitted code &lt;/li&gt;    &lt;li&gt;Other native memory allocated by the CLR &lt;/li&gt;    &lt;li&gt;Native memory allocated by other sub-systems like say a COM module or some other native modules which the managed application P/Invokes into. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The first three is managed by .NET Compact Framework by using &lt;a href="http://blogs.msdn.com/abhinaba/archive/2009/03/30/how-many-heaps-does-the-net-compact-framework-use.aspx"&gt;5 heaps&lt;/a&gt;. The counter mentioned above returns the sum of all bytes allocated in all of the first 3 categories. .NETCF doesn’t keep tab of memory allocated in category #4.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9518976" width="1" height="1"&gt;</content><author><name>abhinaba</name><uri>http://blogs.msdn.com/members/abhinaba.aspx</uri></author><category term="C# / .NET / Coding" scheme="http://blogs.msdn.com/abhinaba/archive/tags/C_2300_+_2F00_+.NET+_2F00_+Coding/default.aspx" /><category term="Garbage Collection" scheme="http://blogs.msdn.com/abhinaba/archive/tags/Garbage+Collection/default.aspx" /></entry></feed>