Powershell/C#:异步调用管道&显示结果 [英] Powershell/C#: Invoking a pipeline asynchronously & displaying the results

查看:46
本文介绍了Powershell/C#:异步调用管道&显示结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此示例-http://msdn.microsoft.com/zh-cn/library/windows/desktop/ee706590(v=vs.85).aspx

我正在尝试以异步方式调用脚本.但是,与此同时,我想向GUI提供有关正在发生的一组操作的反馈,即想吐出在GUI上并行发生在幕后的Write-verbose东西.

I am trying to invoke my script in an async way. But, at the same time, I want to give feedback to the GUI on the set of operations happening i.e. want to spit the Write-verbose stuffs happening behind the scenes parallely on the GUI.

我对实现这一目标感到困惑-因为我看到有一个

I am confused in achieving this - because I see there is a DataReady event on the PipelineReader object ? Is it possible to somehow consume that w.r.t the MSDN sample above such that I can show feedback on the GUI ?

从概念上讲,我无法关联 DataReady 事件.

推荐答案

知道了!这是完整的代码...

首先在表单上添加富文本框= txtOutput &添加对的引用

C:\ Program Files(x86)\ Reference程序集\ Microsoft \ WindowsPowerShell \ v1.0 \ System.Management.Automation.dll

C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll

    IAsyncResult _invokeResult; 

    PowerShell _ps = PowerShell.Create();

    delegate void SetOutput(string value);

    // Monitor the DataAdded
    _ps.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded);

    var sr = new StreamReader(@"C:\MyScript.ps1");
    _ps.AddScript(sr.ReadToEnd());
    _invokeResult = _ps.BeginInvoke<PSObject>(null, null, AsyncInvoke, null);


   void Verbose_DataAdded(object sender, DataAddedEventArgs e)
   {
       System.Diagnostics.Debug.Print( ((PSDataCollection<VerboseRecord>) sender)[e.Index].ToString()) ;

       if (txtOutput.InvokeRequired)
       {
           string msg = ((PSDataCollection<VerboseRecord>) sender)[e.Index].ToString();
           txtOutput.Invoke(new SetOutput(Execute), new object[] { msg} );
       }
   }



   void AsyncInvoke(IAsyncResult ar)
   {
       // end
       try
       {
           _ps.EndInvoke(ar);
       }
       catch (Exception ex)
       {
             // do something with the error...
       }
  }

private void Execute(string msg)
        {
            txtOutput.SelectionFont = new Font(txtOutput.SelectionFont.FontFamily, 9.0f);
            txtOutput.AppendText(msg);
            txtOutput.ScrollToCaret();
        }

这篇关于Powershell/C#:异步调用管道&amp;显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆