我制作了一个简单的 Windows 服务,但是当我尝试启动它时,它会立即关闭并显示以下消息:
本地计算机上的 ConsumerService 服务启动然后停止。如果某些服务没有被其他服务或程序使用,它们会自动停止。
以下是我尝试运行的服务:
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        var servicesToRun = new ServiceBase[] 
                                          { 
                                              new ConsumerService() 
                                          };
        ServiceBase.Run(servicesToRun);
    }
}
public partial class ConsumerService : ServiceBase
{
    private readonly MessageConsumer<ClickMessage> _messageconsumer;
    private readonly SqlRepository _sqlrep;
    private static Timer _timer;
    public ConsumerService()
    {
        InitializeComponent();
    }
    protected override void OnStart(string[] args)
    {
        try
        {
            File.Create(@"c:\ErrorLog.txt");
            WriteToFile("Has started : " + DateTime.UtcNow);
            var t = new Timer(OnTimeEvent, null, 1000, 1000);
        }
        catch (Exception e)
        {
            WriteToFile("Error : " + e.Message);
        }
    }
    private void OnTimeEvent(object state)
    {
        WriteToFile("The time is : " + DateTime.UtcNow);
    }
    protected override void OnStop()
    {
        WriteToFile("Has stopped : " + DateTime.UtcNow);
    }
    private static void WriteToFile(string s)
    {
        var stream = File.AppendText(@"c:\ErrorLog.txt");
        stream.WriteLine(s);
    }
}
如您所见,它只是一个简单的计时器,每 1 秒向文件写入一行,所以我很困惑为什么这会阻止服务运行。我也很难看出 windows 给出的消息与该服务有什么关系,因为这会阻止任何服务运行,除非某些东西已经依赖于它。