How To: Call a Method Asynchronously
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How To: Call a Method Asynchronously

.NET Framework 2.0

You can asynchronously call a method using WMI in .NET Framework by passing in an instance of the ManagementOperationObserver class into the InvokeMethod method. By calling a method asynchronously, you can complete other tasks while the method is being called and executed. If you call the method semisynchronously, you must wait for the method to finish executing before you start any other tasks. For information on calling a method semisynchronously, see How To: Execute a Method.


The following code calls a method asynchronously. The Win32_Process.Create method is called to create a new process for Calc.exe.

using System;
using System.Management;

public class InvokeMethodAsync 

    public InvokeMethodAsync()

        // Get the object on which the method 
        // will be invoked
        ManagementClass processClass = 
            new ManagementClass("Win32_Process");

        // Create a results and completion handler
        ManagementOperationObserver handler = 
            new ManagementOperationObserver();
        handler.Completed += 
            new CompletedEventHandler(Completed);

        // Invoke method asynchronously
        ManagementBaseObject inParams =
        inParams["CommandLine"] = "calc.exe";
            handler, "Create", inParams, null);
        // Do something while method is executing

    private bool isComplete = false;
    private ManagementBaseObject returnObject;

    // Delegate called when the method completes
    // and results are available
    private void NewObject(object sender,
        ObjectReadyEventArgs e) 
        Console.WriteLine("New Object arrived!");
        returnObject = e.NewObject;

    private void Completed(object sender,
        CompletedEventArgs e)
        isComplete = true;

    public static void Main() 
        InvokeMethodAsync wmiMethod = new InvokeMethodAsync();

Compiling the Code

The example requires references to the System and System.Management namespaces.

See Also

© 2015 Microsoft