C#调用外部控制台程序截取输出的问题

已知有个控制台程序,输入"go"它会进行计算,耗费一定时间输出计算过程,计算完毕输出“thebestmoveis.....”,输入"quit"退出。现需要在第一时间截取它... 已知有个控制台程序,输入"go"它会进行计算,耗费一定时间输出计算过程,计算完毕输出“the bestmove is .....”,输入"quit"退出。现需要在第一时间截取它的输出,不知道有没有办法可以判定控制台是否计算完毕?我之前用的个笨法子是go之后 System.Threading.Thread.Sleep(3000);等它运行三秒,但显然是不太合适的。
我的程序:
enginename = "Robbot.exe";
process = new Process();
process.StartInfo.FileName = enginename;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
StreamWriter sw = process.StandardInput;
StreamReader srout = process.StandardOutput;
sw.AutoFlush = true;
sw.WriteLine("go");
System.Threading.Thread.Sleep(3000);
sw.WriteLine("quit");
sw.Close();
string message = srout.ReadToEnd();
srout.Close();
int index = message.IndexOf("bestmove");
string output = message.Substring(index + 9, 4);
展开
 我来答
bigxuanbigxuan
2011-09-30 · 超过40用户采纳过TA的回答
知道答主
回答量:90
采纳率:0%
帮助的人:111万
展开全部
sw.WriteLine("go");
process.WaitForInputIdle();
sw.WriteLine("quit");

WaitForInputIdle是让你当前的进程等待process直到process出现空闲。如果担心意外、不想无期限的等下去,WaitForInputIdle()还有一个重载、接受一个int型的参数,设置其等待的时间(单位毫秒)。
追问
这个控制台程序随时都可以输入,它在运算当中也可以,永远是空闲状态,WaitForInputIdle()无效……
追答
这样啊,那就稍微麻烦一点,得用异步处理了。用BeginOutputReadLine,然后什么都不用管了,下面的事情在process的OutputDataReceived	事件里面处理。

这样的意思就是,开始监听output,一旦process有输出(也就是计算完的“the bestmove is .....”),就在OutputDataReceived做你接下来要做的事情,相当于是等待输出。

具体处理方法可以参考msdn的这两处:
http://msdn.microsoft.com/zh-cn/library/system.diagnostics.process.beginoutputreadline(v=vs.80).aspx

http://msdn.microsoft.com/zh-cn/library/system.diagnostics.process.outputdatareceived(v=vs.80).aspx
蔡德江
2011-09-30 · TA获得超过3187个赞
知道大有可为答主
回答量:1700
采纳率:0%
帮助的人:1408万
展开全部
bool t=true;
if(t)
{
运算完成!
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
Aisix
2011-09-30 · 超过12用户采纳过TA的回答
知道答主
回答量:108
采纳率:0%
帮助的人:63.1万
展开全部
楼上两位正解!
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2011-09-30
展开全部
可以设定一个参数 当运算完为参数赋值 获取时当参数为指定值时 便认为运算完成
追问
我就是不知道它什么时候运算完成……
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式