Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET Applications and the Working Set


.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].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.