How To: Receive Management Information Without Waiting
Access to management information often occurs in distributed environments, and might involve large amounts of data. To support this, management operations can also be performed asynchronously.
The method used to invoke an operation asynchronously is an overload of the synchronous method, with an additional parameter of type ManagementOperationObserver for handling the callbacks for results. This object defines events for notification when results arrive and on completion. You can create handlers and include them in the subscription that execute when these events are generated.
Example
The following code example demonstrates how to query for management information asynchronously. The query is for instances of the Win32_Service class (services running on the local computer), and the name and state of instances of the Win32_Service class are displayed.
using System; using System.Management; // This example demonstrates how // to perform an asynchronous instance enumeration. public class EnumerateInstancesAsync { public EnumerateInstancesAsync() { // Enumerate asynchronously using Object Searcher // =============================================== // Instantiate an object searcher with the query ManagementObjectSearcher searcher = new ManagementObjectSearcher(new SelectQuery("Win32_Service")); // Create a results watcher object ManagementOperationObserver results = new ManagementOperationObserver(); // Attach handler to events for results and completion results.ObjectReady += new ObjectReadyEventHandler(NewObject); results.Completed += new CompletedEventHandler(Done); // Call the asynchronous overload of Get() // to start the enumeration searcher.Get(results); // Do something else while results // arrive asynchronously while (!isCompleted) { System.Threading.Thread.Sleep (1000); } Reset(); } private bool isCompleted = false; private void NewObject(object sender, ObjectReadyEventArgs obj) { Console.WriteLine("Service : {0}, State = {1}", obj.NewObject["Name"], obj.NewObject["State"]); } private void Reset() { isCompleted = false; } private void Done(object sender, CompletedEventArgs obj) { isCompleted = true; } public static void Main() { EnumerateInstancesAsync asyncQuery = new EnumerateInstancesAsync(); } }
Compiling the Code
The example requires references to the System and System.Management namespaces.