建立多個 Runspace
如果您建立大量的運行空間,可以考慮建立運行空間集區。 使用 Runspacepool 物件,而不是使用相同的特性來建立大量的個別執行空間,可以改善效能。
建立和使用運行空間集區。
下列範例顯示如何建立執行時間集區,以及如何在集區的執行時間中以非同步方式執行命令。
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.
}
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應