January 10, 2009

Knowing memory usage from Compact Framework application

For any handheld device application, memory usage is an important element to observer. .NET Compact framework have very less code that gives information about physical or virtual memory. But using native libraries – by doing pInvoke, one can retrieve memory usage statistics.

There can be more than one level of report that can be captured. Today, lets start with summary. GlobalMemoryStatus function in coredll can help identifying how much total physical memory available in the device and how much of it is free. Same way, how much of virtual memory available to process and how much of it is free.

Lets see how can we use GlobalMemoryStatus. We will have to define a class which will be passed to function and will be filled by GlobalMemoryStatus function. Layout of it is defined as structure by MS team, but its alright to use class here. By having it as class, we will be able to write default constructor unlike structure in C#.

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    internal class MemoryStatus
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public uint ullTotalPhys;
        public uint ullAvailPhys;
        public uint ullTotalPageFile;
        public uint ullAvailPageFile;
        public uint ullTotalVirtual;
        public uint ullAvailVirtual;
        public uint ullAvailExtendedVirtual;
        public MemoryStatus()
        {
            this.dwLength = (uint)Marshal.SizeOf(typeof(MemoryStatus));
        }
    }

Now, lets define extern method for GlobalMemoryStatus

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("coredll.dll", CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "GlobalMemoryStatus")]
        static extern bool GlobalMemoryStatusWinCE([In, Out] MemoryStatus lpBuffer);

And here is how we can call the method

    MemoryStatus internalReport = new MemoryStatus();
    if (GlobalMemoryStatusWinCE(internalReport))
	

1 Comment

  1. Very useful post…thank you so much 🙂

    Comment by Talal Shoaib — November 14, 2011 @ 8:14 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress