当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C#实现Window管道技术

ASP.NET
如何在命令行下编译一个asp.net项目
ADO 与ADO.NET
当VS.NET2003遇上VS.NET2005,WebService部署何去何从
昨日关注:逐步解说: 将Web Form网页国际化
在.NET下编写中文代码程序
防止同一个程序多次运行。 [VB.NET]
Visual C#设计多功能关机程序
什么是Web Service?
实现ListView控件的行间隔颜色的优化代码
失去信心?还是再度迷惘(二):Mono only is Mono,not .NET never
在Winform中发HTTP请求(调用WebService服务)
.NET中加密和解密的实现方法 3
notNET中加密和解密的实现方法
.NET中加密和解密的实现方法2
mshtml:javascript为HTML文件中的Select添加option
VS.NET解决方案的兼容问题
关于创建快捷方式的小结
使用 GDI+ 进行双缓冲绘图
如何用DataGrid实现根据日期判断是否显示New标志
昨日关注:C-omega vs ADO.net

ASP.NET 中的 C#实现Window管道技术


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 53 ::
收藏到网摘: n/a


之前发了一篇使用Window API来实现管道技术的文章,后来改用C#来实现相同的效果,发现C#本身方便的进程线程机制使工作变得简单至极,随手记录一下。
首先,我们可以通过设置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();
然后设置线程连续读取输出的字符串:
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 );
线程函数如下:
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(); 为了不阻塞主线程,可以将整个过程放到一个另一个线程里就可以了