c#程序自动化——程序挂起/不工作
本文关键字:程序 工作 挂起 自动化 | 更新日期: 2023-09-27 17:55:02
我一直在尝试编写一个程序,以便在我的计算机上自动运行不同的进程。到目前为止,我已经有了以下程序运行控制台版本的BleachBit(它就像CCleaner),进程出现在任务管理器中,它达到了大约25kb的进程RAM,然后CPU使用率变为0%,只是坐在那里什么都不做,永远不会退出。
我在代码中做错了什么可能导致这种情况发生吗?我试过编辑app.manifest,以确保程序必须以admin身份运行,以防它需要更多特权
同样,当在bat文件中运行类似的代码来运行程序时,它会打开自己的窗口并运行良好,所以我不确定。任何正确方向上的帮助都会很棒。
我正在运行的代码如下。
static void Main(string[] args)
{
string Log = "";
if (File.Exists(Environment.CurrentDirectory + "''BleachBit''bleachbit_console.exe"))
{
Log += "File exists";
Log += RunProgramCapturingOutput("''BleachBit''bleachbit_console.exe", "--preset --clean");
}
else
Log += "Program not found. Please place at ''BleachBit''bleachbit_console.exe";
File.WriteAllText("log.txt", Log);
Console.ReadLine();
}
public static string RunProgramCapturingOutput(string filename, string arguments)
{
ProcessStartInfo processInfo = new ProcessStartInfo()
{
FileName = Environment.CurrentDirectory + filename,
Arguments = arguments,
CreateNoWindow = false,
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(Environment.CurrentDirectory + filename),
RedirectStandardError = false,
RedirectStandardOutput = true
};
Process process = Process.Start(processInfo);
process.WaitForExit();
string output = output = process.StandardOutput.ReadToEnd();
Console.WriteLine("Output: " + output);
process.Close();
return output;
}
将这些行改为
string output = output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
允许避免死锁。由于硬盘I/O的原因,这个程序似乎运行得比较慢,给它一点时间,你就会看到它完成了。
我发现这个死锁问题从https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx
在代码块中声明:"//为了避免死锁,总是先读取输出流,然后等待。"