Esecuzione di metodi in oggetti di gestione

Gli oggetti di gestione contengono proprietà che possono essere lette o modificate, oltre a esporre metodi che possono essere chiamati da un'applicazione client di gestione. Un oggetto disco, ad esempio, può esporre un metodo "format" oppure un oggetto servizio può disporre di metodi "start" e "stop". Nell'esempio seguente viene mostrato il codice necessario per chiamare un metodo in un oggetto di gestione. In questo caso particolare il metodo è statico e viene chiamato sulla stessa classe. Tuttavia, generalmente i metodi vengono richiamati su istanze.

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]);
    }

}

È inoltre possibile eseguire i metodi in modo asincrono. Nell'esempio seguente viene mostrato come effettuare questa operazione:

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;
         }
      }
   }
}

Vedere anche

Accesso alle informazioni di gestione tramite System.Management | Recupero di insiemi di oggetti di gestione | Esecuzione di query per ottenere informazioni di gestione | Sottoscrizione e utilizzo di eventi | Opzioni di servizi remoti e di connessione | Utilizzo di oggetti tipizzati in modo sicuro