如何创建C#异步powershell方法?
因此,我想创建一种异步运行powershell脚本的方法。下面的代码是到目前为止我所拥有的,但它似乎不是异步的,因为它锁定了应用程序,并且输出不正确如何创建C#异步powershell方法?,c#,powershell,asynchronous,async-await,C#,Powershell,Asynchronous,Async Await,因此,我想创建一种异步运行powershell脚本的方法。下面的代码是到目前为止我所拥有的,但它似乎不是异步的,因为它锁定了应用程序,并且输出不正确 public static string RunScript(string scriptText) { PowerShell ps = PowerShell.Create().AddScript(scriptText); // Create an IAsyncResult object and ca
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.fromsync(…)
来获得异步操作的Task
,然后使用wait
原谅我的无知,我对使方法异步的理解不是让方法像这样启动吗。。。公共异步静态任务RunScriptAsync(string scriptText)@user1843359:是,并使用wait
关键字等待异步操作完成。我得到了以下结果:wait Task.Factory.fromsync(_ps.BeginInvoke(),preslt=>_ps.EndInvoke(preslt))代码>