次の方法で共有


管理イベントへのサブスクライブと管理イベントの処理

System.Management 名前空間は、管理イベントにサブスクライブするための機能を提供します。WMI イベントは、マネージ環境にあるオペレーティング システム、デバイス、またはアプリケーション内で発生した事象に関する通知です。管理クライアントは、イベント クエリを指定することによって対象のイベントにサブスクライブできます。イベント クエリは、クエリ実行するイベントの型と、取り出したイベントをさらにフィルタ処理するために使用する条件のセットを定義します。イベントの処理は、同期でも非同期でも実行できます。WMI におけるイベントの詳細については、MSDN の WMI のドキュメントを参照してください。

WMI 組み込みイベントにサブスクライブし、それらのイベントを同期で処理する方法を次のコード例に示します。この例では、イベント クエリを構築し、それを使用して ManagementEventWatcher オブジェクトを初期化し、さらに、指定したフィルタに一致するイベントが送信されるのを待機します。

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

イベントを非同期で処理する方法を次のコード例に示します。この例ではタイマ イベントを使用するため、イベントを毎秒発生させるように WMI タイマを設定し、不要になった時点でそれを削除します。ManagementEventWatcher オブジェクトは、WMI イベントが送信されたときに発生するいくつかの .NET Framework イベントを定義します。これらのイベントには、受信データを処理するためのデリゲートが割り当てられます。

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 

参照

System.Management による管理情報へのアクセス | 管理オブジェクトのコレクションの取得 | 管理情報のクエリ | 管理オブジェクトのメソッドの実行 | リモート管理と接続オプション | 厳密に型指定されたオブジェクトの使用