zoukankan      html  css  js  c++  java
  • C#实现Window管道技术

      管道技术一般采用Window API来实现,最近试着用C#来实现Windows管道技术,发现C#本身方便的进程线程机制使工作变得简单至极,随手记录一下,推荐给大家。

      首先,我们可以通过设置Process类,获取输出接口,代码如下:
     

    1  Process proc = new Process(); 
    2  proc .StartInfo.FileName = strScript; 
    3  proc .StartInfo.WorkingDirectory = strDirectory; 
    4  proc .StartInfo.CreateNoWindow = true
    5  proc .StartInfo.UseShellExecute = false
    6  proc .StartInfo.RedirectStandardOutput = true
    7  proc .Start();

     

      然后设置线程连续读取输出的字符串:
     

    1  eventOutput = new AutoResetEvent(false); 
    2  AutoResetEvent[] events = new AutoResetEvent[1]; 
    3  events[0= m_eventOutput; 
    4
    5  m_threadOutput = new Thread( new ThreadStart( DisplayOutput ) ); 
    6  m_threadOutput.Start(); 
    7  WaitHandle.WaitAll( events );


      线程函数如下:
     

     1  private void DisplayOutput() 
     2  
     3   while ( m_procScript != null && !m_procScript.HasExited ) 
     4   
     5   string strLine = null
     6   while ( ( strLine = m_procScript.StandardOutput.ReadLine() ) != null
     7   
     8    m_txtOutput.AppendText( strLine + "\r\n" ); 
     9    m_txtOutput.SelectionStart = m_txtOutput.Text.Length; 
    10    m_txtOutput.ScrollToCaret(); 
    11   }
     
    12   Thread.Sleep( 100 ); 
    13   }
     
    14   m_eventOutput.Set(); 
    15  }

      这里要注意的是,使用以下语句使TextBox显示的总是最新添加的,而AppendText而不使用+=,是因为+=会造成整个TextBox的回显使得整个显示区域闪烁 
     

    1  m_txtOutput.AppendText( strLine + "\r\n" ); 
    2  m_txtOutput.SelectionStart = m_txtOutput.Text.Length; 
    3  m_txtOutput.ScrollToCaret();
    4
  • 相关阅读:
    双飞翼布局和圣杯布局的对比
    阿里云centos+java环境搭建
    Android零散知识点积累
    [转]linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例
    [转]linux shell 获取当前正在执行脚本的绝对路径
    [转+整理]linux shell 将字符串分割成数组
    [转]linux shell 数组建立及使用技巧
    linux shell 入门
    jquery 字符串转为json
    JQuery插件开发入门
  • 原文地址:https://www.cnblogs.com/net66/p/199950.html
Copyright © 2011-2022 走看看