进程访问超时时出错

编程入门 行业动态 更新时间:2024-10-26 07:23:57
本文介绍了进程访问超时时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好 我有这个方法来执行命令

private static int ExecuteCommand(string command,int timeout) { var processInfo = new ProcessStartInfo(cmd.exe,/ C+ command) { CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = C:\\,}; var process = Process.Start(processInfo); process.WaitForExit(timeout); var exitCode = process.ExitCode; process.Close(); 返回exitCode; }

有时我会在 var exitCode = process.ExitCode;

例外情况是:

流程必须在请求之前退出信息可以确定。

解决方案

好的,非常好。但这意味着你不需要这个 process.ExitCode 值,因为它在通话时没有任何意义。这有什么问题?您可以使用这个非常条件,即具有此异常的事实,告诉进程的状态:在try-catch块中将此属性调用三明治,并查看是否有此异常。 :-) 更严重的是,您可以通过提前检查 process.HasExited 来实现: msdn.microsoft/en-us /library/system.diagnostics.process.hasexited%28v=vs.110%29.aspx [ ^ ]。 你看,你调用process.WaitForExit(timeout);显然是阻止电话。它将调用线程置于等待状态:系统切换出你的线程,并且在唤醒之前不会将其安排回执行,它没有浪费CPU时间这段等待。可以通过多种原因唤醒线程,其中一个是超时。因此,当执行过去时,你不知道醒来的确切原因。您可以通过检查进程状态找到它。 顺便说一下,在交互式UI应用程序中,它是在单独的线程中执行此类操作的原因,不是UI线程。
-SA

Hello I have this method to execute commands

private static int ExecuteCommand(string command, int timeout) { var processInfo = new ProcessStartInfo("cmd.exe", "/C " + command) { CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = "C:\\", }; var process = Process.Start(processInfo); process.WaitForExit(timeout); var exitCode = process.ExitCode; process.Close(); return exitCode; }

some times i get an exception in

var exitCode = process.ExitCode;

the exception is:

Process must exit before requested information can be determined.

解决方案

All right, very nice. But it means you don't need this process.ExitCode value, because it makes no sense at the moment of the call. What's wrong with that? You can use this very condition, the fact of having this exception, to tell the state of the process: sandwich this property call in try-catch block and see if you have this exception. :-) More seriously, you can do it by checking process.HasExited in advance: msdn.microsoft/en-us/library/system.diagnostics.process.hasexited%28v=vs.110%29.aspx[^]. You see, you call process.WaitForExit(timeout); is apparently a blocking call. It puts the calling thread in a wait state: the system switches out your thread and does not schedule it back to execution until it is waken up, it wastes no CPU time for the wait. The thread can be waken up by a number of reasons, and one of them is timeout. So, when the execution goes past to the call, you don't know exact reason of waking up. You can find it out by checking up the process status. By the way, in interactive UI applications it would be the reason to execute such things in a separate thread, not a UI thread.
—SA

更多推荐

进程访问超时时出错

本文发布于:2023-11-27 02:54:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!