訂閱和使用管理事件
System.Management 命名空間提供訂閱管理事件的機能。WMI 事件是用來告知管理環境中,作業系統、裝置或應用程式發生的事件。管理用戶端指定事件查詢來訂閱相關事件,該事件查詢定義了必要的事件類型以及用來進一步篩選傳遞事件的各種狀況。消費事件也可以使用同步和非同步方式進行。如需 WMI 事件的詳細資料,請參閱 MSDN 的 WMI 文件。
下列程式碼範例顯示如何訂閱 WMI 內建事件,和如何使用同步方式消費該事件。這個範例建立 (Build) 一個事件查詢,並使用它來初始化 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 物件定義了數個 .NET Framework 事件,傳遞 WMI 事件後便會引發這些事件。委派將被附加到這些事件以便處理內送的資料。
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 存取管理資訊 | 擷取管理物件集合 | 查詢管理資訊 | 執行管理物件上的方法 | 遠端和連接選項 | 使用強式型別物件