Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建C#异步powershell方法?_C#_Powershell_Asynchronous_Async Await - Fatal编程技术网

如何创建C#异步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

因此,我想创建一种异步运行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.fromsync(…)
来获得异步操作的
Task
,然后使用
wait

原谅我的无知,我对使方法异步的理解不是让方法像这样启动吗。。。公共异步静态任务RunScriptAsync(string scriptText)@user1843359:是,并使用
wait
关键字等待异步操作完成。我得到了以下结果:
wait Task.Factory.fromsync(_ps.BeginInvoke(),preslt=>_ps.EndInvoke(preslt))