繁体   English   中英

如何创建C#异步Powershell方法?

[英]How to create C# async powershell method?

因此,我想创建一种异步运行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<PSObject> ,然后使用await

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM