Creazione di più spazi di esecuzione
Se si crea un numero elevato di spazi di esecuzione, è consigliabile creare un pool di spazi di esecuzione. L'uso di un oggetto System.Management.Automation.Runspaces.Runspacepool, anziché creare un numero elevato di singoli spazi di esecuzione con le stesse caratteristiche, può migliorare le prestazioni.
Creazione e uso di un pool di spazi di esecuzione.
L'esempio seguente illustra come creare un pool di spazi di esecuzione e come eseguire un comando in modo asincrono in uno spazio di esecuzione del pool.
namespace HostRunspacePool
{
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
/// <summary>
/// This class provides the Main entry point for the Host application.
/// </summary>
internal class HostRunspacePool
{
/// <summary>
/// This sample demonstrates the following.
/// 1. Creating and opening a runspace pool.
/// 2. Creating a PowerShell object.
/// 3. Adding commands and arguments to the PowerShell object.
/// 4. Running the commands asynchronously using the runspace
/// of the runspace pool.
/// </summary>
/// <param name="args">Parameter is not used.</param>
private static void Main(string[] args)
{
// Create a pool of runspaces.
using (RunspacePool rsp = RunspaceFactory.CreateRunspacePool())
{
rsp.Open();
// Create a PowerShell object to run the following command.
// get-process wmi*
PowerShell gpc = PowerShell.Create();
// Specify the runspace to use and add commands.
gpc.RunspacePool = rsp;
gpc.AddCommand("Get-Process").AddArgument("wmi*");
// Invoke the command asynchronously.
IAsyncResult gpcAsyncResult = gpc.BeginInvoke();
// Get the results of running the command.
PSDataCollection<PSObject> gpcOutput = gpc.EndInvoke(gpcAsyncResult);
// Process the output.
Console.WriteLine("The output from running the command: get-process wmi*");
for (int i= 0; i < gpcOutput.Count; i++)
{
Console.WriteLine(
"Process Name: {0} Process Id: {1}",
gpcOutput[i].Properties["ProcessName"].Value,
gpcOutput[i].Properties["Id"].Value);
}
} // End using.
} // End Main entry point.
} // End HostPs5 class.
}
Vedere anche
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per