Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

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.

Example

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 =
            processClass.GetMethodParameters("Create");
        inParams["CommandLine"] = "calc.exe";
        processClass.InvokeMethod(
            handler, "Create", inParams, null);
      
        // Do something while method is executing
        while(!isComplete) 
        {
            System.Threading.Thread.Sleep(1000);
        }
    }

    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

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.