强制外部进程在一段时间后被终止
我有一个从 C# 类库运行的命令行可执行文件。在极少数情况下,可执行文件会因传递给它的命令行数据而挂起。不幸的是,这会导致调用 c# DLL 的应用程序挂起,同时无限期地等待进程退出。
如果命令行 exe 没有在 1 秒内完成执行,它就永远不会退出。我想做的是在进程启动后立即生成一个计时器,如果进程在几秒钟内没有退出,则强制关闭该进程。
这里最好的方法是什么?该解决方案需要对性能产生最小的影响,因为此命令行进程是高度重复性任务的瓶颈。
编辑:为什么我应该使用 System.Timer 而不是 Threading.Timer,反之亦然?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = workingDirectory;
startInfo.FileName = commandLineExe;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = strArguments;
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
请避免提出我应该尝试找出命令行应用程序挂起的原因,或者我应该使用的建议将命令行功能重构到源代码中。我们正在积极解决这个问题,但应用程序的稳定性需要放在第一位。
I have a command line executable that is run from a C# class library. In some very rare situations the executable will hang because of the command line data passed to it. Unfortunetely this causes the application calling the c# DLL to hang whilst it waits indefinitely for the process to exit.
If the command line exe doesnt finish execution within 1 second its never going to exit. What I'd like to do is spawn a timer just after the process has started and force close the process if it hasnt exited within a few seconds.
What is the best approach here? The solution needs to have minimal impact upon performance because this command line process is the bottleneck in a highly repetitive task.
Edit: Any reason why I should use System.Timer rather than Threading.Timer or vice versa?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = workingDirectory;
startInfo.FileName = commandLineExe;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = strArguments;
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
Please refrain from suggestions that I should try and figure out why the command line app is hanging, or that I should refactor the command line functionality into the source code. We are actively working on that problem but stability of the application needs to come first.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需添加:
Just add: