繁体   English   中英

在一段时间后强制终止外部进程

[英]Force external process to be killed after time period

我有一个从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();
            }

请不要提出建议,我应该尝试弄清为什么命令行应用程序挂起,或者应该将命令行功能重构为源代码。 我们正在积极地解决这个问题,但是应用程序的稳定性需要首先考虑。

只需添加:

// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo)) {
    if(!exeProcess.WaitForExit(1000))
          exeProcess.Kill();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM