Skip to content

Avoid polling registry keys in .NET (C#)

Some days ago I read an article at The Old New Thing about performance cost of reading a registry key. As I am reading registry keys in quite frequently I wonderd how to avoid polling registry keys in .NET (C#). Windows API provides a function RegNotifyChangeKeyValue which notifies the caller about changes. Sadly, this function is not provided by the Microsoft.Win32.RegistryKey. So I tried writing a wrapper class for this.

I don't claim that this is perfect, so any comment would be appreciated !

Downloads:

RegistryKeyMonitor 0.1 (source and binaries)

Usage:

C#:
  1. using System;
  2. using System.Threading;
  3. using Microsoft.Win32;
  4.  
  5. namespace RegistryKeyMonitorTester
  6. {
  7.     class Tester
  8.     {
  9.         [STAThread]
  10.         public static void Main() {
  11.             RegistryHive[] hives = new RegistryHive[]{RegistryHive.CurrentUser, RegistryHive.LocalMachine};
  12.             string[] subkeys = new string[]{"Environment","SoftwareMicrosoft"};
  13.             RegistryKeyMonitor.Monitor monitor = new RegistryKeyMonitor.Monitor(hives, subkeys);
  14.             monitor.RegKeyChanged += new EventHandler(monitor_RegKeyChanged);
  15.             monitor.Error +=new System.IO.ErrorEventHandler(monitor_Error);
  16.             monitor.Start();
  17.             LongRunningTask();
  18.             monitor.Stop();
  19.         }
  20.  
  21.         private static void LongRunningTask() {
  22.             for(int i=0; i<60; ++i) {
  23.                 Console.WriteLine("Try changing some registry keys");
  24.                 Thread.Sleep(1000);
  25.             }
  26.         }
  27.  
  28.         private static void monitor_RegKeyChanged(object sender, EventArgs e) {
  29.             RegistryKeyMonitor.RegKeyChangedEventArgs ea = (RegistryKeyMonitor.RegKeyChangedEventArgs) e;
  30.             Console.WriteLine("RegistryKey " + ea.RegHive.ToString() + "" + ea.RegSubKey + " changed.");
  31.         }
  32.  
  33.         private static void monitor_Error(object sender, System.IO.ErrorEventArgs e) {
  34.             Console.WriteLine(e.GetException().ToString());
  35.         }
  36.     }
  37. }

Categories: Programming.

Tags: , ,

Comment Feed

No Responses (yet)



Some HTML is OK

or, reply to this post via trackback.