windows 服务(带计时器)在没有控制台的情况下无法工作

windows service (with timer) not working without console

我用 Timers.Timer 创建了一个 windows 服务。 如果我 运行 作为控制台应用程序工作正常,但如果我将设置更改为 windows 应用程序并且我评论所有控制台功能,则计时器不工作。用 Console.ReadLine();都好。但我不应该打开控制台。

 protected override void OnStart(string[] args)
    {
        AutoLog = false;
        SetTimer();
        Console.ReadLine();//if remove this line dont works
    }

设置定时器()

private void SetTimer()
    {
        mytimer = new Timer();
        mytimer.Interval = 2000;
        mytimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        mytimer.Enabled = true;
    }

OnTimedEvent()

 private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        mytimer.Enabled = false;
        EventLog evento1 = new EventLog();
        evento1.Source = "scPublicar";
        evento1.Log = "Publicar";
        evento1.WriteEntry("Publicación corriendo,  OnTimedEvent");
        mytimer.Enabled = true;
    }

Program.cs 主线()

 static void Main(string[] args)
    {
        ServiceBase[] servicesToRun;
        servicesToRun = new ServiceBase[] { new Publicar() };
        if (Environment.UserInteractive)
        {
            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                onStartMethod.Invoke(service, new object[] { new string[] { } });
            }
        }
        else
            ServiceBase.Run(servicesToRun);
    }

感谢您的回答

当您 运行/调试 Visual Studio 中的代码时,Environment.UserInteractivetrue 并且进程立即停止。此行为是设计使然,您不应该做任何事情让它等待(例如调用 Console.ReadLine())。

您需要 运行 您的代码作为 Windows 服务(而不是控制台应用程序),然后它将由服务控制管理器管理。这意味着您可以将其配置为在系统启动时自动启动并保持 运行ning。您还可以通过 Windows 管理控制台 (services.msc) 中的服务 Snap-In 启动和停止它。但要使其正常工作,您首先需要安装您的服务。

按照以下步骤操作:

  1. Create a new 'Windows Service' project。您会注意到输出类型已设置为 'Windows Application'。
  2. 将您的代码粘贴到新的 Program.cs 文件中并删除 Console.ReadLine() 语句
  3. Add an installer
  4. Install the service
  5. 运行services.msc。您应该找到一个名为 'Service1' 的服务。 Right-click 开始吧。
  6. 转到事件日志,您将每 2 秒找到一个条目

参考文献: