windows服务在电脑开机时不执行OnStart功能

The windows service does not do the OnStart function when the PC turns on

我一直在编写 windows 服务,该服务在 PC 打开和关闭时执行 SQL 服务器插入数据库。

当我手动启动服务和手动关闭它时,它会插入,但在电脑打开和关闭时它不起作用。我是不是做错了什么?

我使用 Windows 服务 (.NET) 项目编写 Visual Studio 代码。

谢谢

我留下了部分代码(OnStart,OnShutdown)所以你可以看看我做了什么:

// OnStart
protected override void OnStart(string[] args)
{
    try
    {
        InsertaObrir();
    }
    catch (Exception)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("Error Start: " + "\n");
        File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
        sb.Clear();
     }
}

// OnShutdown
protected override void OnShutdown()
{
    try
    {
        InsertaSortir();
    }
    catch (Exception)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("Error Sortir: " + "\n");
        File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
        sb.Clear();
    }
}

// IntentaObrir 
private void InsertaObrir()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("Inicia: " + DateTime.Now + "\n");
    File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
    sb.Clear();

    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = Properties.Settings.Default.IP;
    builder.UserID = Properties.Settings.Default.UserID;
    builder.Password = Properties.Settings.Default.Password;
    builder.InitialCatalog = Properties.Settings.Default.BaseDeDades;

    int num = CreateCommand(builder.ConnectionString, true); 
    // This line works so it's not the problem

    sb.Append("Inserta -> " + num + "\n");
    File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
    sb.Clear();
}

// IntentaSortir
private void InsertaSortir()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("Apaga: " + DateTime.Now + "\n");
    File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
    sb.Clear();

    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = Properties.Settings.Default.IP;
    builder.UserID = Properties.Settings.Default.UserID;
    builder.Password = Properties.Settings.Default.Password;
    builder.InitialCatalog = Properties.Settings.Default.BaseDeDades;

    int num = CreateCommand(builder.ConnectionString, false);

    // This line works so it's not the problem
    sb.Append("Inserta -> " + num + "\n");
    File.AppendAllText(Properties.Settings.Default.RutaArxiuLog, sb.ToString());
    sb.Clear();
}

我发现 Windows 10 有一个快速启动,使 OnStart 不触发(以及 OnShutdown)。

我会留下 post 我找到它的地方,还有一个解释如何禁用此功能的网站。

谢谢

https://help.uaudio.com/hc/en-us/articles/213195423-How-To-Disable-Fast-Startup-in-Windows-10