所以我想创建一种异步运行 powershell 脚本的方法。下面的代码是我到目前为止的代码,但它似乎不是异步的,因为它锁定了应用程序并且输出不正确。
public static string RunScript(string scriptText)
{
PowerShell ps = PowerShell.Create().AddScript(scriptText);
// Create an IAsyncResult object and call the
// BeginInvoke method to start running the
// pipeline asynchronously.
IAsyncResult async = ps.BeginInvoke();
// Using the PowerShell.EndInvoke method, get the
// results from the IAsyncResult object.
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject result in ps.EndInvoke(async))
{
stringBuilder.AppendLine(result.Methods.ToString());
} // End foreach.
return stringBuilder.ToString();
}
最佳答案
您正在异步调用它。
但是,您通过调用 EndInvoke()
来同步等待异步操作完成,从而破坏了目的。 .
要实际异步运行它,您也需要使您的方法异步。
您可以通过调用 Task.Factory.FromAsync(...)
来做到这一点得到 Task<PSObject>
对于异步操作,然后使用 await
.
关于c# - 如何创建 C# 异步 powershell 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17640575/