如何创建C#异步方法的PowerShell? [英] How to create C# async powershell method?
问题描述
所以,我想创建一个方法来异步运行PowerShell脚本。下面code是我到目前为止,但似乎并没有被异步因为它锁定了应用程序和输出不正确。
公共静态字符串了RunScript(字符串scriptText)
{
PowerShell的PS = PowerShell.Create()AddScript(scriptText)。 //创建一个IAsyncResult对象,并调用
// BeginInvoke方法开始运行
//管道是异步的。
IAsyncResult的异步= ps.BeginInvoke(); 使用方法PowerShell.EndInvoke //,得到
//从IAsyncResult对象的结果。
StringBuilder的StringBuilder的=新的StringBuilder();
的foreach(PSObject结果ps.EndInvoke(异步))
{
stringBuilder.AppendLine(result.Methods.ToString());
} //结束的foreach。 返回stringBuilder.ToString();
}
您是异步调用它。
不过,随后通过同步等待异步操作完成,通过调用击败目的 EndInvoke会()
。
要实际运行它以异步方式,你需要让你的方法也同步。结果
你可以通过调用 Task.Factory.FromAsync(...)
获得任务< PSObject>
的异步操作,然后使用等待
。
So I want to create a way to run a powershell script asynchronously. The below code is what I have so far, but it doesn't seem to be async because it locks up the application and the output is incorrect.
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();
}
You are calling it asynchronously.
However, you are then defeating the purpose by synchronously waiting for the asynchronous operation to finish, by calling EndInvoke()
.
To actually run it asynchronously, you need to make your method asynchronous too.
You can do that by calling Task.Factory.FromAsync(...)
to get a Task<PSObject>
for the asynchronous operation, then using await
.
这篇关于如何创建C#异步方法的PowerShell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!