MobileDevice.Hibernate and Garbage Collection

You Can Take it With You

Syndication

News

  • Don't miss the next Windows Mobile Webcast... Unit Testing for Mobile Devices: http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032382824&EventCategory=4&culture=en-US&CountryCode=US.

Since posting the message about MobileDevice.Hibernate a few days ago, I’ve been thinking a lot about the relationship between the .NET CF Garbage Collector and Windows Mobile; specifically, the CLR’s handling of WM_HIBERNATE and that handling’s affect on a .NET CF application.

 

As mentioned in Wednesday’s post, .NET CF 2.0 applications are strongly encouraged to handle the MobileDevice.Hibernate event and as part of handling the event, release as many resources as possible without loosing the application’s state. Failing to release resources, can negatively impact both your application as well as other applications running on the device.

 

Calling Dispose on all members that provide a Dispose implementation is a good start at returning resources but in most .NET CF applications the majority of application resources are associated with managed memory. As we know, .NET CF applications cannot explicitly return managed memory. Rather, all that can be done is to stop using the memory (a.k.a. make the memory unreachable). The way we usually do this is to set the associated references to null.

 

This is where I started questioning what to do next. The unreachable memory won’t be returned until a GC collection occurs. So this made me wonder if maybe one should call GC.Collect as the last statement in the Hibernate event handler; however, doing so didn’t feel right as application code is generally discouraged from calling GC.Collect.

 

The only choice of what to do next – put in some research and try to understand what the CLR does in response to a WM_HIBERNATE...

 

And what-do-ya-know – the CLR does the right thing; it calls GC.Collect for you.

 

The CLR’s handling of WM_HIBERNATE goes like this:

  • Receive WM_HIBERNATE from OS
  • Fire the MobileDevice.Hibernate event
  • Call GC.Collect
  • Release unused pages from the GC heap back to the OS

So the end result is that the CLR makes application handling of MobileDevice.Hibernate event easy: call Dispose on disposable members and set references to large objects to null. The one thing to remember is that you want to provide a consistent experience for the user so you need to balance freeing memory with maintaining your application’s state.

 


Posted Oct 21 2005, 02:47 PM by jim-wilson

Add a Comment

(required)  
(optional)
(required)  
Remember Me?