【发布时间】:2018-06-14 01:45:58
【问题描述】:
在 Windows 10 中,我创建了一个在启动时初始化的在后台运行的进程。当计算机进入睡眠状态时,它会使 Windows 崩溃并给我一个 BSOD。
我愿意接受任何解决方案,但是我目前正试图在“暂停”PowerModeChanged 事件发生时终止该进程。在机器进入休眠状态之前,这似乎不足以杀死进程,并且机器仍在崩溃。我的 PowerModeChanged 监听器肯定在工作,它肯定是导致机器崩溃的辅助进程。
我对后台进程开发有点陌生,我整天都在尝试不同的方法,但进展不大。肯定有人必须有这方面的经验并且知道解决方法。
// Application path and command line arguments
static string ApplicationPath = @"C:\path\to\program.exe";
static Process ProcessObj = new Process();
static void Main(string[] args)
{
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
startProcess();
Console.ReadKey();
}
static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
Console.WriteLine(e.Mode.ToString());
if (e.Mode == PowerModes.Suspend)
{
ProcessObj.Kill();
}
if (e.Mode == PowerModes.Resume)
{
startProcess();
}
}
static void startProcess()
{
// Create a new process object
try
{
// StartInfo contains the startup information of the new process
ProcessObj.StartInfo.FileName = ApplicationPath;
// These two optional flags ensure that no DOS window appears
ProcessObj.StartInfo.UseShellExecute = false;
ProcessObj.StartInfo.CreateNoWindow = true;
// This ensures that you get the output from the DOS application
ProcessObj.StartInfo.RedirectStandardOutput = true;
// Start the process
ProcessObj.Start();
// Wait that the process exits
ProcessObj.WaitForExit();
// Now read the output of the DOS application
string Result = ProcessObj.StandardOutput.ReadToEnd();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
【问题讨论】:
-
虽然你说这是一个“后台进程”,但看起来它实际上是作为前台进程运行的。请说明您如何在启动时启动此程序。换句话说,你如何导致
Main()方法被调用? -
我认为 op 意味着静默应用程序,而不是 Windows 服务或较低级别的系统进程。虽然 StartProcess 或 ProcessStart 是 windows 服务的入口点。
-
用这个链接戳电脑眼睛-blog.backslasher.net/windows-awake-ps.html
-
噢!过了一分钟,OnStart() 是 Service 派生的重载。
-
听起来我在最初的方法中找错了树,但为了回答你的问题,我有 2 个程序,一个运行我放置在 /Startup/ 目录中的代码。另一个程序是代码示例中的 ApplicationPath 变量示例的辅助应用程序。我正在更新它以采用 Windows 服务路线。谢谢!
标签: c# windows-10 background-process sleep-mode