当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

Visual C#中实现Window管道技术

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:55:32

:2010-08-31 07:04:00

管道技术一般采用Window API来实现,在C#中实现管道技术其实也很简单,因为C#中有方便的进程和线程机制。

(1)通过设置Process类,获取输出接口,代码如下:

Process proc = new Process();
        proc .StartInfo.FileName = strScript;
        proc .StartInfo.WorkingDirectory = strDirectory;
        proc .StartInfo.CreateNoWindow = true;
        proc .StartInfo.UseShellExecute = false; 
        proc .StartInfo.RedirectStandardOutput = true;
        proc .Start();

(2)设置线程连续读取输出的字符串:

eventOutput = new AutoResetEvent(false);
        AutoResetEvent[] events = new AutoResetEvent[1];
        events[0] = m_eventOutput;

m_threadOutput = new Thread( new ThreadStart( DisplayOutput ) );
        m_threadOutput.Start();
        WaitHandle.WaitAll( events );

(3)完整线程函数:

private void DisplayOutput()
        {
         while ( m_procScript != null && !m_procScript.HasExited )
         {
          string strLine = null;
          while ( ( strLine = m_procScript.StandardOutput.ReadLine() ) != null)
          {
           m_txtOutput.AppendText( strLine + "\r\n" );
           m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
           m_txtOutput.ScrollToCaret();
          }
          Thread.Sleep( 100 );
         }
         m_eventOutput.Set();
        }

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

m_txtOutput.AppendText( strLine + "\r\n" );

m_txtOutput.SelectionStart = m_txtOutput.Text.Length;

m_txtOutput.ScrollToCaret();

为了不阻塞主线程,可以将整个过程放到一个另一个线程里。



Visual C#中实现Window管道技术