# Tuesday, 23 January 2007

So.. you've got this cool Pocket PC .Net CF 2.0 application, which reads off a SQL Server Compact Edition database, everything works fine when you're in debugging mode, then as you're testing the app you get the dreaded OutOfMemory exception thrown when you try to open a connection to the database.

You go to the memory app under settings and notice that the Pocket PC only has 1MB of program memory left, obviously it can't load the SQLCE runtime AND do your queries at the same time. You hit the running programs tab and select close all, but you don't expect a user to do that. There must be a better way to do this!

The OS is supposed to close applications in low memory situations, but exactly how low is LOW? Gleamed from the Pocket PC SDK we find this little tidbit:-

The Shell in a Windows Mobile-based Smartphone sends WM_CLOSE messages if there is less than 128 KB of free memory. The shell does not send WM_CLOSE messages if you ask for more memory than is available. For example, the Smartphone does not allocate 200 KB of memory if it only has 190 KB free. Instead, the shell displays an Out Of Memory dialog box to the user.

Wow.. 128KB is what the OS considers to be low... so what can we do about it? Well we call the function which the snippet above was taken from, SHCloseApps. What this API function does is that you pass the amount of memory you want and the OS will keep sending WM_CLOSE messages to applications until the memory requested is achieved. To use the function in your PPC program first you need to declare the P/Invoke in your class (For C# examples.. well start reading the documentation on how to do P/Invokes!)

Public Declare Function SHCloseApps Lib "aygshell" (ByVal MemorySought As Int32) As Boolean

Then when you need to, just call the function with the number of bytes of memory you need.


Simple and gets the job done, before I did this my app kept getting OutOfMemory exceptions (no thanks to the RSSReader, GPS Map program AND Pocket IE) during execution. Now it just works... like it should.

PS. Here's another tip, you might want to use this function if you ever want the user to take a picture with the device's builtin camera, cause they usually need about 1~2MB to take a 1MP picture, so be sure to free up some memory BEFORE you show the picture selector dialog box.

Note that you can Post As GUEST as well.
blog comments powered by Disqus
Tuesday, 23 January 2007 21:42:32 (Malay Peninsula Standard Time, UTC+08:00)
Hehehehehe so you gonna do it for my pocket pc or not hehehehehe...
Tuesday, 23 January 2007 23:44:45 (Malay Peninsula Standard Time, UTC+08:00)
Dude.. this is for programming lar.
Wednesday, 24 January 2007 14:12:13 (Malay Peninsula Standard Time, UTC+08:00)
So you can't write me an app to automatically switch of my idle programs???
Comments are closed.