繁体   English   中英

如何让我的 Windows 服务保持活动状态?

[英]How do i keep my windows service alive?

我做了一个简单的 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 给出的消息与此服务有什么关系,因为这会阻止任何服务运行,除非某些服务已经依赖它。

这很可能是由于主线程中未处理的错误造成的。 要验证这一点,请检查事件日志,但从快速查看您的代码来看,函数WriteToFile有可能崩溃并导致整个服务崩溃。

实际上它应该崩溃,因为您将流保持打开状态(因此文件被锁定)并且第二次尝试打开它会导致错误。

将代码更改为此,它应该可以防止此类崩溃并修复您将文件锁定的错误:

private static void WriteToFile(string s)
{
    try
    {
        using (var stream = File.AppendText(@"c:\ErrorLog.txt"))
        {
            stream.WriteLine(s);
            stream.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("error writing to file: " + e);
        //...or any other means of external debug...
    }
}

正如我所看到的,您的代码正在结束......因此程序的执行自然结束。 这就是您的服务也停止的原因,因为它的执行结束了。

msdn

只要您在使用 Timer,就必须保留对它的引用。 与任何托管对象一样,当没有对 Timer 的引用时,它会受到垃圾回收的影响。 Timer 仍然处于活动状态的事实并不能阻止它被收集。

您不会保留对Timer对象的任何引用。

尝试改变这个:

private static Timer _timer;

对此:

private Timer _timer;

和这个:

var t = new Timer(OnTimeEvent, null, 1000, 1000);

对此:

_timer = new Timer(OnTimeEvent, null, 1000, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM