如何创建C#async powershell方法?

时间:2013-07-14 15:03:49

标签: c# powershell asynchronous async-await

所以我想创建一种异步运行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();
    }

1 个答案:

答案 0 :(得分:7)

你是异步调用它。

然而,您通过调用EndInvoke()同步等待异步操作完成,从而打败了目的。

要实际异步运行,您需要使方法异步。
您可以通过调用Task.Factory.FromAsync(...)为异步操作获取Task<PSObject>,然后使用await来完成此操作。