管道技術(shù)一般采用Window API來實(shí)現(xiàn),最近我試著用C#來實(shí)現(xiàn)Windows管道技術(shù),發(fā)現(xiàn)C#本身方便的進(jìn)程線程機(jī)制使工作變得簡(jiǎn)單至極,隨手記錄一下,推薦給大家。
首先,我們可以通過設(shè)置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();
然后設(shè)置線程連續(xù)讀取輸出的字符串:
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 );
線程函數(shù)如下:
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而不使用+=,是因?yàn)?=會(huì)造成整個(gè)TextBox的回顯使得整個(gè)顯示區(qū)域閃爍
m_txtOutput.AppendText( strLine + "\r\n" );
m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
m_txtOutput.ScrollToCaret();
為了不阻塞主線程,可以將整個(gè)過程放到一個(gè)另一個(gè)線程里就可以了
首先,我們可以通過設(shè)置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();
然后設(shè)置線程連續(xù)讀取輸出的字符串:
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 );
線程函數(shù)如下:
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而不使用+=,是因?yàn)?=會(huì)造成整個(gè)TextBox的回顯使得整個(gè)顯示區(qū)域閃爍
m_txtOutput.AppendText( strLine + "\r\n" );
m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
m_txtOutput.ScrollToCaret();
為了不阻塞主線程,可以將整個(gè)過程放到一個(gè)另一個(gè)線程里就可以了

