Windows服务(带计时器)没有控制台无法正常工作

时间:2018-03-07 22:35:00

标签: c# .net console windows-services system.timers.timer

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

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

SetTimer的()

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 Main()

 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);
    }

感谢您的回答

1 个答案:

答案 0 :(得分:1)

在Visual Studio中运行/调试代码时,Environment.UserInteractivetrue,进程立即停止。此行为是设计使然,您不应该做某事让它等待(例如,呼叫Console.ReadLine())。

您需要将代码作为Windows服务(而不是控制台应用程序)运行,然后由服务控制管理器进行管理。这意味着您可以将其配置为在系统启动时自动启动并继续运行。您也可以通过Windows管理控制台(services.msc)中的服务管理单元启动和停止它。但要实现这一点,首先需要安装您的服务。

请按照以下步骤操作:

  1. Create a new 'Windows Service' project。您会注意到输出类型已设置为“Windows应用程序”。
  2. 将代码粘贴到新的Program.cs文件中,然后删除Console.ReadLine()语句
  3. Add an installer
  4. Install the service
  5. 运行services.msc。您应该找到一个名为“Service1”的服务。右键单击它以启动它。
  6. 转到事件日志,您将每2秒找到一个条目
  7. 参考文献: