Ricco E
Ricco E

Reputation: 95

How do i keep my windows service alive?

I have made a simple windows-service, but when i try to start it it shuts down immediately with the following message:

The ConsumerService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.

Following is the service i try to run:

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

As you can see, it's only a simple timer writing a line to a file every 1 second, so i'm puzzled why this should prevent the service from running. I also have a hard time to see how the message given by windows is in any way related to this service, as that would prevent any service from running unless something is already depending on it.

Upvotes: 3

Views: 5147

Answers (3)

Mike de Klerk
Mike de Klerk

Reputation: 12328

As what I can see your code is ending... Hence the execution of the program comes to a natural end. That is why your service stops also, because its execution ended.

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66399

This is most likely due to unhandled error in the main thread. To verify this check the event log, but from quick view of your code the function WriteToFile has the chance to crash and bring the whole service down with it.

Actually it ought to crash because you leave the stream open (thus the file is locked) and second attempt to open it will result in error.

Change the code to this and it should prevent such crash plus fix your bug of leaving the file locked:

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...
    }
}

Upvotes: 2

Grzegorz W
Grzegorz W

Reputation: 3517

From msdn:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

You don't keep any reference to your Timer object.

Try changing this:

private static Timer _timer;

to this:

private Timer _timer;

And this:

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

to this:

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

Upvotes: 0

Related Questions