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.
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
WriteToFilehas 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: