Sunday, August 16, 2009

Calling Process.Modules reliably

Namespace System.Diagnostics contains the class Process. With this class you can determine how many modules your process has loaded, even across multiple domains. There is a catch, however, since accessing the property Process.Modules may throw a Win32Exception. This property may be empty in which case Microsoft's documentation recommends to use WaitForInputIdle() to before retrieving the property. Before you access it you don't know, and if you do and it is empty at that point you'll get the Win32Exception. You can also call Process.WaitForInputIdle() just before you access Process.Modules, just to be on the safe side. However, using WaitForInputIdle() may throw an exception as well in certain circumstances. I couldn't find this exception mentioned in the documentation for WaitForInputIdle(), though. Therefore I decided to create a little helper method to make retrieving Process.Modules more reliable. Here is my code:
private static int GetModuleCount() {
  var currentProcess = Process.GetCurrentProcess();
  try {
     return currentProcess.Modules.Count;
  }
  catch(Win32Exception) {
     // Wait until input message is empty and retry.
     currentProcess.WaitForInputIdle();
     return currentProcess.Modules.Count;
  }
}
The first attempt assumes that the message loop is empty and the process in idle. If that call fails the code assumes that indeed more messages need to be processed so it waits until no further input needs to be processed. Then it simply tries again. If you need this method in several places in your code then you may also want to consider to create it as an extension method for class Process. I didn't implement the above code as an extension method since I needed it only in once place (hence it is a private method).

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!