Compartir a través de


Ejecutar métodos en objetos de administración

Los objetos de administración contienen propiedades que se pueden leer o cambiar, y también pueden exponer métodos a los que una aplicación cliente de administración puede llamar. Por ejemplo, un objeto disco podría exponer un método "formato" o un objeto servicio podría tener métodos "iniciar" y "detener". En el ejemplo siguiente se muestra el código para invocar a un método en un objeto de administración. En este caso concreto, el método es estático y la llamada se realiza en la propia clase; no obstante, lo normal es llamar a los métodos en instancias.

using System;
using System.Management;

public class InvokeMethod {

    public static void Main() {

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

      // Option 1: Invocation using parameter objects
      //================================================

      //Get an input parameters object for this method
      ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

      //Fill in input parameter values
      inParams["CommandLine"] = "calc.exe";

      //Execute the method
      ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);

      //Display results
      //Note: The return code of the method is provided in the "returnValue" property of the outParams object
      Console.WriteLine("Creation of calculator process returned: " + outParams["returnValue"]);
      Console.WriteLine("Process ID: " + outParams["processId"]);

      // Option 2: Invocation using args array
      //=======================================

      //Create an array containing all arguments for the method
      object[] methodArgs = {"notepad.exe", null, null, 0};

      //Execute the method
      object result = processClass.InvokeMethod ("Create", methodArgs);

      //Display results
      Console.WriteLine ("Creation of process returned: " + result);
      Console.WriteLine ("Process id: " + methodArgs[3]);
    }

}

La ejecución de los métodos también puede realizarse de forma asincrónica. En el ejemplo siguiente se muestra cómo:

using System;
using System.Management;

public class InvokeMethodAsync {

    public static void Main() {

      //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();
      ObjectReadyHandler objHandler = new ObjectReadyHandler();
        handler.ObjectReady += new ObjectReadyEventHandler(objHandler.NewObject);

      // 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(!objHandler.IsComplete) {
         System.Threading.Thread.Sleep(1000);
      }

      //After execution is completed, display results
      Console.WriteLine("Creation of calculator process returned: " + objHandler.ReturnObject["returnValue"]);
      Console.WriteLine("Process ID: " + objHandler.ReturnObject["processId"]);

    }

   public class ObjectReadyHandler   {

      private bool isComplete = false;
        private ManagementBaseObject returnObject;

      //Delegate called when the method completes and results are available
      public void NewObject(object sender, ObjectReadyEventArgs e) {
         Console.WriteLine("New Object arrived!");
         ReturnObject = e.NewObject;
         isComplete = true;
      }

      //Property allows accessing the result object in the main function
      public ManagementBaseObject ReturnObject {
         get {
            return returnObject;
         }
      }

      //Used to determine whether the method execution has completed
      public bool IsComplete {
         get {
            return isComplete;
         }
      }
   }
}

Vea también

Acceso a la información de administración con System.Management | Recuperar colecciones de objetos de administración | Consultar información de administración | Suscribir y consumir eventos | Interacción remota y opciones de conexión | Utilizar objetos con establecimiento inflexible de tipos