如何避免标准输入卡在c#进程中 [英] How to avoid standard input getting stuck in c# process

查看:43
本文介绍了如何避免标准输入卡在c#进程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来检查提交代码是否正确.这是我的一些代码...

I'm writing a program to check whether the submit code is right or not. Here is some of my code...

Process submitProg;
StreamWriter progInput;
string input;//it will be submitProg's standard input

//initialization
//...

submitProg.Start();
progInput = submitProg.StandardInput;
progInput.Write("{0}",input);
progInput.Close();
progInput.Dispose();


while(!submitProg.HasExited)
    if(timeOUT)
        submitProg.Kill();

令人惊讶的是,它会卡在 progInput.Write("{0}",input); 行,而输入足够大并且提交程序没有读取任何内容.

Amazingly it will get stuck at the line progInput.Write("{0}",input); while input is big enough and the submit program didn't read anything.

一些提交代码可能很棘手,比如 while(1); 什么都不做.当输入文件足够小时,我可以终止该进程.相反,如果输入文件较大,程序将不会检查超时并在读取输入时卡住.

Some submit code might be tricky like while(1); doing nothing. I can kill the process when the input file is small enough. On the contrary, if the input file is bigger, the program won't check for timeout and get stuck while reading input.

我有什么解决方案可以避免陷入不读取任何内容的代码中.谢谢.

Do I have any solution to avoid getting stuck in the code that doesn't read anything. Thanks.

推荐答案

您受标准输入缓冲区的大小和您正在测试的程序的影响.如果它不读取其缓冲区,则您对标准输入的写入可能会阻塞.

You're at the mercy of the size of the standard input buffer and the program you're testing. If it doesn't read its buffer, your write to the standard input can block.

避免该问题的一种方法是在不同线程(例如 ThreadPool 线程)上写入标准输入流.只需将 Write、Close、Dispose 行放在 ThreadPool 任务中并使用 ThreadPool.QueueUserWorkItem.

One way to avoid that issue would be to write to the standard input stream on a different thread, eg a ThreadPool thread. Just place the Write, Close, Dispose lines in a ThreadPool task and use ThreadPool.QueueUserWorkItem.

作为旁注,您可能不需要调用 progInput.Close 和 ProgInput.Dispose.Dispose 调用应该没问题.

As a side note, you probable don't need to call progInput.Close and ProgInput.Dispose. The Dispose call should be fine.

这篇关于如何避免标准输入卡在c#进程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆