Rya*_*rah 10 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();
}
Run Code Online (Sandbox Code Playgroud)
你是异步调用它.
但是,通过调用同步等待异步操作完成,您就会失败EndInvoke()
.
要实际异步运行它,您还需要使方法异步.
您可以通过调用Task.Factory.FromAsync(...)
获取Task<PSObject>
异步操作然后使用来实现await
.
归档时间: |
|
查看次数: |
7347 次 |
最近记录: |