Dispatches from Maine

Just another person of little note writing about ordinary things. That I reside in Maine is icing on the cake.

12 September 2005

PDC05: Day One (Resource Management in Managed Code)

After a brief break, Anson Tsao took the stage again with "Resource Management in Managed Code." Much like his previous talk, he began with a core position which the talk would be based on: "garbage collection is not resource management." He made an excellent case that the focus of garbage collection is memory in particular rather than resources in general. Since developers new to garbage collected systems often overlook this distinction, resources are the new major element being leaked. For instance, failing to explicitly release WinForms objects, which are really wrappers around an HWND, can lead to HWND depletion and a resource shortfall.

He provided a list of common pitfalls:
  • Keeping references to dead objects (always NULL your handles)
  • Implicit boxing
  • Pinning young objects (causes gc heap fragmentation since it blocks compacting)
  • GC.Collection considered harmful (it screws up the heuristics)
  • Finalization (too late for releasing resources)
The last point is more complex than it seems. He indicated that even though finalization is not where you ought to release resources, you should still do it there as well as a "just in case" step, however, your handles might already be gone.

He then provided a list of new tools available in Visual Studio 2005 which can help with resource management:
  • auto_handle (smart pointers for managed objects)
  • SafeHandle (deals with releasing OS handles in long-running processes)
  • HandleCollector (hints to the gc to run a collection cycle when the handle count is too high)
  • AddMemoryPressure()/RemoveMemoryPressure() (tells the gc to ignore blocks of native memory, which would otherwise signal a memory shortfall to the gc)
  • msclr::com::ptr<> (provides a smart pointer system for managed code using COM objects)
  • protected regions (still not clear about this one...)
  • CLR Profiler Beta 2 (download)
The talk was simply excellent and I walked away with a large number of tools which will be essential when we start to switch from unmanaged to managed code. Of all the presenters so far, Anson is the best on technical depth and clarity.


Post a Comment

Links to this post:

Create a Link

<< Home