C# Windows Service

我与影子孤独终老i 提交于 2019-12-02 10:21:19

Typically you would want something like this. As Joe mentioned in the comments you want Start to initialize and release control to another thread to make sure that you return within 30 seconds.

private readonly ProcessMonitor processMonitor = new ProcessMonitor();

protected override void OnStart(string[] args)
{
    processMonitor.Start();
}

protected override void OnStop()
{
    processMonitor.Stop();
}

In a Service there is no concept of a readline - there's no keyboard. I wouldn't be surprised if this is throwing an exception at that call. Have you checked your Application Log?

Well... A service doesn't have a console input/output. So the ReadLine won't stop it from executing.

What does ProcessMonitor do?

Typically, for services your code lives in a thread that monitors whether the service has been stopped or paused.

OnStart() must complete and end successfully for the service to be considered "Started"

Move your Console.ReadLine(); into your ProcessMonitor() constructor, and create your ProcessMonitor inside the constructor for the service. Your OnStart method can be empty. Despite what people are saying the Console methods will NOT crash your service, however it is probably not best practice. I guess the proper way to keep a service running (after your timers are started) is to use a while loop with a Thread.Sleep(60000) inside it.

When I am writing a service I put all the functionality in a Class Library project, then I create a Console Application project to test the service functionality, and then a Windows Service project. Both the Console Application and Windows Service project call one method in the Class Library to start the service functionality. If you use this technique you can call Console.WriteLine in the Class Library which can be viewed when running the Console Application. PS Topshelf is overrated, writing a windows service is not that difficult.

public partial class ProcessMonitor_Service : ServiceBase
{

    public ProcessMonitor_Service()
    {
        InitializeComponent();            
        ProcessMonitor pm = new ProcessMonitor();
    }

    protected override void OnStart(string[] args)
    {

    }

    protected override void OnStop()
    {

    }
}

public class ProcessMonitor
{
    public ProcessMonitor()
    {
        // start timers
        Console.ReadLine(); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!