如何创建C#async powershell方法?

所以我想创建一种异步运行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()同步等待异步操作完成,从而EndInvoke()了目的。

要实际异步运行它,您还需要使方法异步。
您可以通过调用Task.Factory.FromAsync(...)来获取异步操作的Task ,然后使用await