Windows服务-操作系统关闭太快

本文关键字:操作系统 服务 Windows | 更新日期: 2023-09-27 18:14:19

首先我要为我的英语道歉。我尝试创建一个Windows服务,在电脑关闭时运行备份数据程序。问题是操作系统在关机期间杀死我的Windows服务之前,备份数据是由执行到结束的。我将注册表值HKEY_LOCAL_MACHINE'SYSTEM'CurrentControlSet'Control'WaitToKillServiceTimeout更改为3600000,但它没有帮助,我的Windows服务在执行之前被杀死。也许有人知道如何让操作系统不会像备份数据那样快地杀死Windows服务。请帮助我,我在等待你的回复。下面我包括我的代码Windows Service:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.IO;
    namespace backUp_ser
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
                this.CanShutdown = true;
            }
            protected override void OnStart(string[] args)
            {
            }
            protected override void OnStop()
            {
            }
            protected override void OnShutdown()
            {
                ProcessStartInfo stratInfo = new ProcessStartInfo();
                stratInfo.WindowStyle = ProcessWindowStyle.Hidden;
                stratInfo.FileName = "C:''Program Files''Cobian Backup 10''Cobian.exe";
                stratInfo.Arguments = "list:C:''Program Files''Cobian Backup 10''DB''MainList.lst -bu -nogui -autoclose";
                Process process = Process.Start(stratInfo);
                process.WaitForExit(360000);
            }
        }
    }

Windows服务-操作系统关闭太快

除了你的查询,我想提醒你,服务是在一个单独的登录会话中运行的,服务不会与登录的桌面会话交互(大部分)。

因此,您需要在服务代码中拦截关机事件。然后,您需要保持关机事件,直到完成备份过程。你可以通过消息泵/队列来挂钩那些Windows事件。你需要拦截WM_ENDSESSION/WM_QUERYENDSESSION事件。

这个查询已经在本文中讨论过了。你可以参考