While attempting to start my Windows Service the following error suddenly appears when the status bar is almost at 50 % :
Error 1053: The service did not respond to the start or control request in timely fashion
When I check the Event Viewer I see the following errors:
Application: EnvMonService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception
Exception Info: System.NullReferenceException
Stack: at EnvMonService.EnvMonService..ctor() at EnvMonService.Program.Main()
I cannot see where the error comes from - here is my code:
Main()
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new EnvMonService()
};
ServiceBase.Run(ServicesToRun);
}
Constructor
public EnvMonService()
{
InitializeComponent();
}
OnStart and OnStop
protected override void OnStart(string[] args)
{
// Start a task thread polling the databse for changes and updates the ASCII file
mainTask = new Task(PollDatabase, cts.Token, TaskCreationOptions.LongRunning);
mainTask.Start();
}
protected override void OnStop()
{
// Cancel Task and wait for it to be disposed
cts.Cancel();
mainTask.Wait();
}
My Variables
// Connection to database
private string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
// Newest timestamp
private Int32 latestDate;
// Log file
public LogFileWriter logFileWriter;
// Define datastructure POCO class
EnvDataModel model = new EnvDataModel();
// Instantiate a concellation token for a task
private CancellationTokenSource cts = new CancellationTokenSource();
// Instantiate a task
private Task mainTask = null;
// Define a waiting interval between each database polling
private TimeSpan WaitAfterSuccessInterval = new TimeSpan(0, 1, 0);
// Define a waiting interval if any errors happens
private TimeSpan WaitAfterErrorInterval = new TimeSpan(0, 2, 0);
Code running in the Task
private void PollDatabase()
{
// New token
CancellationToken cancellation = cts.Token;
// Fencepost problem
// Setup default interval
TimeSpan interval = TimeSpan.Zero;
// Create a new logfile instance
logFileWriter = new LogFileWriter(@"C:\LogFile.txt");
// Poll database until service stops
while (!cancellation.WaitHandle.WaitOne(interval))
{
try
{
// Poll database here and assign reponse to EnvDataModel
// Update status in logfile
logFileWriter.WriteToLogFile("Database Last Polled: " + DateTime.Now + Environment.NewLine);
// Call ASCII File Parser
ParseDataToASCIIFileAsync();
// Occasionally check the cancelation state
if (cancellation.IsCancellationRequested)
{
break;
}
interval = WaitAfterSuccessInterval;
}
catch (Exception caught)
{
// Log exception
logFileWriter.WriteToLogFile(caught.Message);
// Wait a few minutes before trying again
interval = WaitAfterErrorInterval;
}
}
}