.NET Applications and the Working Set

A .NET app might claim a lot more memory than it needs for its working set. Use this pair of unmanaged functions to trim the extra megabytes


February 06, 2003
URL:http://drdobbs.com/net-applications-and-the-working-set/184416804

.NET Applications and Working Set

Try this: Compile the following code and run it. Then start up the task manager and look at the amount of memory that the application consumes. Here’s the code:

using System;

using System.Windows.Forms;

 

class App

{

   static void Main()

   {

      Application.Run(new Form());

   }

}

It doesn't do much, does it? All this application does is show a blank form on the desktop, and yet on my machine it uses 5.3 MB (as they say, your mileage may vary)! What is happening here is that when the application starts, it has to start up the .NET run time, load the Windows Forms assemblies and JIT compile your code. All of this takes up memory.

Now try this: Minimize the application and look at Task Manager again. On my machine the application uses a 'mere' 388 KB, which rises to 1.2 MB when the form is restored. (It is interesting to note that that this useless application is using more than a quarter of the memory of the state-of-the-art machine that I was using 12 years ago, but I will not dwell on the ravenous memory consumption of modern day applications.)

When you minimize an application, the operating system assumes that you do not want to interact with the application and it makes the application working set (the number of physical pages used by the application) zero. The operating system "wipes the slate clean, treating the application as if it does not need any physical memory (although its "virtual memory usage will remain the same). Of course, even when minimized the application will still be processing the message loop and, thus, it needs some physical memory. The system gives the application the memory it requests, but only as much as it actually needs. The assemblies that are not being used will be paged out of physical memory into the paging file. When the application is restored, this mechanism continues-and since the application will be doing more processing, it will need more memory.

So the solution to the application running with a large working set is simple-make sure that somewhere in the application initialization it minimizes and then restores its main window:

class MyForm : Form

{

   public MyForm()

   {

      this.WindowState = FormWindowState.Minimized;

      this.WindowState = FormWindowState.Normal;

   }

}

This looks like it will perform the required action, but in actual fact, it has no effect on the working set. The reason is that although the .NET object is being created in the constructor, the actual resource hungry item- the window-is not created until the Visible property is set to True by Application.Run(). This occurs well after the constructor has completed. Thus, you need to perform this trimming of the working set after the window has shown. You could do this by setting a timer to go off a few seconds after the constructor has completed, or you could use the Load event:

public MyForm()

{

   this.Load += new EventHandler(this.Loaded);

}

protected void Loaded(object sender, EventArgs args)

{

   this.WindowState = FormWindowState.Minimized;

   this.WindowState = FormWindowState.Normal;

}

The Load event is an artifact of the roots of the Windows Forms library in Visual Basic 6. This event is raised when the window has been created.

I feel a little uneasy about minimizing the window to trim the working set, so instead I use an unmanaged function that is designed to do this. In fact, there are two. If you are running a variant of NT, you will have the process status API (PSAPI) library, so you can use the EmptyWorkingSet() function:

[DllImport("psapi")]

static extern int EmptyWorkingSet(IntPtr handle);

protected void Loaded(object sender, EventArgs args)

{

   EmptyWorkingSet(Process.GetCurrentProcess().Handle);

}

The parameter is the handle of the process. If you do not have PSAPI, then you can use SetProcessWorkingSetSize(), exported from kernel32.dll, to set the working set to zero:

[DllImport("kernel32")]

static extern bool SetProcessWorkingSetSize(IntPtr handle, int minSize, int maxSize);

protected void Loaded(object sender, EventArgs args)

{

   SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);

}

Setting the minimum and maximum size of the working set to 1 instructs the function to trim the working set to zero, after which the working set is allowed to grow to the size that is actually needed by the application.

This final solution is what you need: It ensures that once the application has started, the working set is adjusted to the actual size needed and any assemblies that are not needed are paged out of physical memory. As you perform more work in your application, some of the paged assemblies will be needed, other assemblies will be loaded, and some assemblies that have already been loaded will not be used. Consequently, the working set will require adjustments to keep it as efficient as possible. The operating system will do this automatically, but you can preempt this by calling SetProcessWorkingSetSize() at regular intervals.


Richard Grimes speaks at conferences and writes extensively on .NET, COM, and COM+. He is the author of Developing Applications with Visual Studio .NET (Addison-Wesley, 2002). If you have comments about this topic, Richard can be reached at [email protected].

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.