c# - 如何创建 C# 异步 powershell 方法?

标签 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();
    }

最佳答案

您正在异步调用它。

但是,您通过调用 EndInvoke() 来同步等待异步操作完成,从而破坏了目的。 .

要实际异步运行它,您也需要使您的方法异步。
您可以通过调用 Task.Factory.FromAsync(...) 来做到这一点得到 Task<PSObject>对于异步操作,然后使用 await .

关于c# - 如何创建 C# 异步 powershell 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17640575/

相关文章:

c# - 可重复的复杂正则表达式,带点 '.' 分隔符

用于在 xml 中查找键/值的正则表达式

powershell - 在powershell中传递空日期时间参数

javascript - 如何处理依赖于多个其他异步函数的异步函数

c# - 有条件地锁定资源

c# - 为什么我无法调整表格以适应显示器的尺寸? (Windows 窗体)

c# - 扩展 Telerik 客户端模板列并获取通过的值

c# - 比较日期时发生 StackOverflowException

powershell - 在Powershell中运行一个exe,并在执行该exe后关闭cmd提示符

java - 使用 CompletableFuture 代替 API 的 Future