PowerShell的C#异步执行 [英] Powershell C# asynchronous execution
问题描述
我想在C#中异步执行PowerShell脚本。我使用的BeginInvoke
方法,但我不能让即使我已经附加了他们代表输出/错误。这里是我的C#code:
I want to execute a Powershell script asynchronously in C#. I've used BeginInvoke
method but I can't get the output/errors even though I've attached delegates for them. Here is my C# code:
using(ps=PowerShell.Create())
{
PSDataCollection<PSObject> output=new PSDataCollection<PSObject>();
output.DataAdded+=output_DataAdded;
ps.AddScript(RenewalScript);
SecureString ss = new SecureString();
for (int i = 0; i < Password.Length; i++)
ss.AppendChar(Password.ElementAt(i));
PSCredential cred = new PSCredential(Username, ss);
ps.AddParameter("Credential", cred);
ps.AddParameter("BuildServer", Server);
ps.AddParameter("CAServer", CAServer);
ps.AddParameter("CAName", CAName);
ps.Streams.Error.DataAdded += Error_DataAdded;
var result=ps.BeginInvoke<PSObject, PSObject>(null, output);
}
void output_DataAdded(object sender, DataAddedEventArgs e)
{
//display output in UI
}
void Error_DataAdded(object sender, DataAddedEventArgs e)
{
//display error message in UI
}
我在我的脚本多个写输出
语句。然而,永远不会触发 DataAdded
方法。但是,当我使用同步调用
方法就可以触发。
I have multiple Write-Output
statements in my script. However, the DataAdded
methods are never triggered. But they are triggered when I use the synchronous Invoke
method.
推荐答案
的看到这个答案。
要真正运行它以异步方式,你需要让你的方法也同步。
你可以通过调用 Task.Factory.FromAsync(...)
获得任务&LT; PSObject&GT;
的异步操作,然后使用等待
。
See this answer.
To actually run it asynchronously, you need to make your method asynchronous too.
You can do that by calling Task.Factory.FromAsync(...)
to get a Task<PSObject>
for the asynchronous operation, then using await
.
这篇关于PowerShell的C#异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!