Subscribing to and Consuming Management Events

The System.Management namespace provides facilities for subscription to management events. WMI events are notifications about occurrences in the operating system, devices, or applications in the managed environment. Management clients can subscribe to events of interest by specifying an event query, which defines the type of events wanted as well as a set of conditions that can be used to further filter the events delivered. Consumption of events can also be done in a synchronous as well as asynchronous way. For details on events in WMI, see the WMI documentation in MSDN.

The following code example shows how to subscribe to WMI intrinsic events and consume them in a synchronous fashion. The example builds an event query, uses it to initialize a ManagementEventWatcher object, and then waits for events that match the specified filter to be delivered.

using System;
using System.Management;

// This example shows synchronous consumption of events. The client 
// is blocked while waiting for events. See additional example for
// asynchronous event handling.

public class EventWatcherPolling {
   public static int Main(string[] args) {
      // Create event query to be notified within 1 second of 
      // a change in a service
      WqlEventQuery query = 
         new WqlEventQuery("__InstanceModificationEvent", 
                         new TimeSpan(0,0,1), 
                       "TargetInstance isa \"Win32_Service\"");

      // Initialize an event watcher and subscribe to events 
      // that match this query
      ManagementEventWatcher watcher = new ManagementEventWatcher(query);
      
      // Block until the next event occurs 
      // Note: this can be done in a loop if waiting for 
      //        more than one occurrence
      ManagementBaseObject e = watcher.WaitForNextEvent();

      //Display information from the event
      Console.WriteLine(
         "Service {0} has changed, State is {1}", 
          ((ManagementBaseObject)e["TargetInstance"])["Name"],
          ((ManagementBaseObject)e["TargetInstance"])["State"]);

      //Cancel the subscription
      watcher.Stop();
      return 0;
    }
}

[Visual Basic]
Imports System
Imports System.Management

' This example shows synchronous consumption of events. The client 
' is blocked while waiting for events. See additional example for 
' asynchronous event handling.

Public Class EventWatcherPolling   
   Overloads Public Shared Function Main(args() As String) As Integer
      ' Create event query to be notified within 1 second of 
      ' a change in a service
      Dim query As New WqlEventQuery( _
         "__InstanceModificationEvent", _
         New TimeSpan(0, 0, 1), _
         "TargetInstance isa ""Win32_Service""")

      ' Initialize an event watcher and subscribe to events 
      ' that match this query
      Dim watcher As New ManagementEventWatcher(query)

      'Block until the next event occurs 
      'Note: this can be done in a loop if waiting for more 
      '       than one occurrence
      Dim e As ManagementBaseObject = watcher.WaitForNextEvent()

      'Display information from the event
      Console.WriteLine( _
         "Service {0} has changed, State is {1}", _ 
         CType(e("TargetInstance"), ManagementBaseObject)("Name"), _
         CType(e("TargetInstance"), ManagementBaseObject)("State"))

      'Cancel the subscription
      watcher.Stop()
      Return 0
   End Function 'Main
End Class 'EventWatcherPolling

The next code example consumes events asynchronously. In this case, the example uses timer events, so the example also sets up a WMI timer to raise an event every second, and removes it when no longer needed. The ManagementEventWatcher object defines several .NET Framework events which are raised when WMI events are delivered. Delegates are attached to these events for handling the incoming data.

using System;
using System.Management;

// This example shows asynchronous consumption of events. In this example 
// you are listening for timer events. The first part of the example sets 
// up the timer.

public class EventWatcherAsync {
    public static int Main(string[] args) {
      // Set up a timer to raise events every 1 second
      //=============================================
      ManagementClass timerClass = 
         new ManagementClass("__IntervalTimerInstruction");
      ManagementObject timer = timerClass.CreateInstance();
      timer["TimerId"] = "Timer1";
      timer["IntervalBetweenEvents"] = 1000;
      timer.Put();

        // Set up the event consumer
      //==========================
      // Create event query to receive timer events
      WqlEventQuery query = 
         new WqlEventQuery("__TimerEvent", "TimerId=\"Timer1\"");

      // Initialize an event watcher and subscribe to 
      // events that match this query
      ManagementEventWatcher watcher = new ManagementEventWatcher(query);

      // Set up a listener for events
      watcher.EventArrived += 
         new EventArrivedEventHandler((new EventHandler()).HandleEvent);

      // Start listening
      watcher.Start();

      // Do something in the meantime
      System.Threading.Thread.Sleep(10000);
      
      // Stop listening
      watcher.Stop();
      return 0;
   }
}

public class EventHandler {
   public void HandleEvent(object sender, EventArrivedEventArgs e)   {
      Console.WriteLine("Event arrived !");
   }
}

[Visual Basic]
Imports System
Imports System.Management

' This example shows asynchronous consumption of events. In this example 
' you are listening for timer events. The first part of the example sets 
' up the timer.

Public Class EventWatcherAsync  
   Overloads Public Shared Function Main(args() As String) As Integer
      ' Set up a timer to raise events every 1 second
      '=============================================
      Dim timerClass As New ManagementClass("__IntervalTimerInstruction")
      Dim timer As ManagementObject = timerClass.CreateInstance()
      timer("TimerId") = "Timer1"
      timer("IntervalBetweenEvents") = 1000
      timer.Put()

      ' Set up the event consumer
      '==========================
      ' Create event query to receive timer events
      Dim query As New WqlEventQuery("__TimerEvent", "TimerId=""Timer1""")

      ' Initialize an event watcher and subscribe to 
      ' events that match this query
      Dim watcher As New ManagementEventWatcher(query)

      ' Set up a listener for events
      Dim handler As New EventHandler()
      AddHandler watcher.EventArrived, AddressOf handler.HandleEvent      

      ' Start listening
      watcher.Start()

      ' Do something in the meantime
      System.Threading.Thread.Sleep(10000)

      ' Stop listening
      watcher.Stop()
      Return 0
   End Function
End Class

Public Class EventHandler
   Public Sub HandleEvent(sender As Object, e As EventArrivedEventArgs)
      Console.WriteLine("Event arrived !")
   End Sub 
End Class 

See Also

Accessing Management Information with System.Management | Retrieving Collections of Management Objects | Querying for Management Information | Executing Methods on Management Objects | Remoting and Connection Options | Using Strongly-typed Objects