Compartir a través de


Suscribir y consumir eventos de administración

El espacio de nombres System.Management proporciona servicios para suscribirse a eventos de administración. Los eventos WMI son notificaciones de lo que ocurre en el sistema operativo, en los dispositivos o en las aplicaciones del entorno administrado. Los clientes de administración pueden suscribirse a eventos relevantes, para lo que especifican una consulta de evento que define el tipo de eventos deseado, así como un conjunto de condiciones que pueden servir para filtrar más los eventos entregados. El consumo de eventos también se puede realizar de manera sincrónica y asincrónica. Para obtener más información acerca de los eventos en WMI, vea la documentación de WMI en MSDN.

En el ejemplo de código siguiente se muestra cómo realizar una suscripción a eventos intrínsecos de WMI y consumirlos de manera sincrónica. En el ejemplo se crea una consulta de eventos, se utiliza para inicializar un objeto ManagementEventWatcher y, después, se espera a que se entreguen los eventos que cumplan las condiciones especificadas como filtro.

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

En el código siguiente se consumen los eventos de manera asincrónica. En este caso, se usan eventos de temporizador, así que en el ejemplo también se configura un temporizador WMI para que genere un evento por segundo y se quite cuando ya no sea necesario. El objeto ManagementEventWatcher define varios eventos de.NET Framework que se generan cuando se entregan eventos de WMI. Con el fin de controlar los datos entrantes, se asocian delegados a estos eventos.

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 

Vea también

Acceso a la información de administración con System.Management | Recuperar colecciones de objetos de administración | Consultar información de administración | Ejecutar métodos en objetos de administración | Interacción remota y opciones de conexión | Utilizar objetos con establecimiento inflexible de tipos