C#在计算机进入睡眠模式之前终止进程

时间:2018-06-14 01:45:58

标签: c# windows-10 background-process sleep-mode

在Windows 10中,我创建了一个在Startup中初始化的后台运行的进程。当计算机进入睡眠状态时,它会崩溃窗口并给我一个BSOD。

我对任何解决方案持开放态度,但是我正在尝试在'Suspend'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);
        }
    }

1 个答案:

答案 0 :(得分:2)

在Windows操作系统平台上,当一个人真正希望为整个运行的计算机运行“后台进程”,并使该进程在电源事件(例如休眠)中生存时,他们通常将其进程设计为Windows服务。

许多流行的应用程序都是作为Windows服务实现的,例如Microsoft SQL Server或Window自己的Web服务器(W3SVC)。

通过选择创建“Windows服务”类型的新项目,可以在Visual Studio中构建Windows服务。

使用此技术,您可以响应多个事件,包括以下内容(在System.ServiceProcess.ServiceBase中定义):

  • OnStart(string[] args)
  • OnStop()
  • OnPause()
  • OnContinue()
  • OnPowerEvent(PowerBroadcastStatus powerStatus)
  • OnShutdown()

您可以在此处找到有关构建.NET Windows服务的更多信息:https://docs.microsoft.com/en-us/dotnet/framework/windows-services/