gpt4 book ai didi

c# - 管道可以在同一个运行空间中并发运行吗?

转载 作者:太空狗 更新时间:2023-10-29 21:54:03 24 4
gpt4 key购买 nike

如何在同一运行空间中并行运行两个 cmdlet。我正在使用 C#。

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.AuthorizationManager = new AuthorizationManager("MyShellId");
iss.ImportPSModule(new string[] { "MSOnline" });
Runspace powerShellRunspace = RunspaceFactory.CreateRunspace(iss);

在两个线程中,我将使用相同的运行空间运行 cmdlet。

Pipeline pipeLine = powerShellRunspace.CreatePipeline();
pipeLine.Commands.Add(shellCommand);
pipeLine.Input.Close();
pipeLine.Invoke();
pipeLine.Output.DataReady += new EventHandler(processData); //processData is a method which processes data emitted by pipeline as and when it comes to avoid out of memory
if (pipeLine.Error != null && pipeLine.Error.Count > 0) {
Collection<Object> errors = (Collection<Object>)(pipeLine.Error.ReadToEnd());
//process those errors
}

但是当两个线程同时使用相同的运行空间来运行 cmdlet 时。我遇到异常,“管道未执行,因为管道已经在执行。管道不能同时执行。”

出于性能原因,我需要使用相同的运行空间。如何实现我的目标?

最佳答案

你看过System.Management.Automation.Runspaces.RunspacePool了吗?类(class)?使用它和 InitialSessionState 可以帮助消除模块导入的开销,因为它只在每个池而不是每个运行空间完成一次。如果您正在寻找 powershell 命令的异步执行,这里是一个非常基本的、非生产就绪的示例:(请注意,我不是在使用 Visual Studio 的计算机上,但这应该是正确的)

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.AuthorizationManager = new AuthorizationManager("MyShellId");
iss.ImportPSModule(new string[] { "MSOnline" });
#set commands we want to run concurrently
string[] commands = new string[4] {
"Start-Sleep -Seconds 5; 'Hi from #1'",
"Start-Sleep -Seconds 7; 'Hi from #2'",
"Start-Sleep -Seconds 3; 'Hi from #3'",
"throw 'Danger Will Robinson'"
};
Dictionary<PowerShell, IAsyncResult> dict = new Dictionary<PowerShell, IAsyncResult>();
//this loads the InitialStateSession for all instances
//Note you can set the minimum and maximum number of runspaces as well
using(RunspacePool rsp = RunspaceFactory.CreateRunspacePool(iss))
{
rsp.SetMinRunspaces(5);
rsp.SetMaxRunspaces(10);
rsp.Open();
foreach(string cmd in commands)
{
PowerShell ps = PowerShell.Create();
ps.AddScript(cmd);
ps.RunspacePool = rsp;
//Add parameters if needed with ps.AddParameter or ps.AddArgument
dict.Add(ps,ps.BeginInvoke());
}
do{
List<PowerShell> toBeRemoved = new List<PowerShell>();
foreach(KeyValuePair<PowerShell, IAsyncResult> kvp in dict)
{
if(kvp.Value.IsCompleted)
{
try
{
PSDataCollection<PSObject> objs = kvp.Key.EndInvoke(kvp.Value);
foreach(PSObject obj in objs)
{
Console.WriteLine(obj);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
toBeRemoved.Add(kvp.Key);
}
}
}
foreach(PowerShell item in toBeRemoved)
{
dict.Remove(item);
}
//Wait before we check again
Thread.Sleep(200);
} while (dict.Count > 0)
rsp.Close();
}
//Added to keep console open
Console.Read();

这应该给出:

Hi from #3
Hi from #1
Hi from #2

关于c# - 管道可以在同一个运行空间中并发运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24332039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com