Error 1053 service didnot respond to start or control request - c#

I am learning window service from msdn link :
http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx
I have properly created , install first Time ....when I try to start it from Service.msc ..it is throwing Error :
Error 1053 service didnot respond to start or control request
this is my Code :
public partial class ASMSService : ServiceBase
{
private Timer myTimer;
TimeSpan setTime;
private DateTime previousDate;
private DateTime todaysDate;
public ASMSService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
myTimer = new System.Threading.Timer(new TimerCallback(TimerAction1));
SetTimer(11, 07, 00);
}
protected override void OnStop()
{
}
private void SetTimer(int hours, int minutes, int seconds)
{
todaysDate = DateTime.Today;
previousDate = todaysDate.AddDays(-1);
setTime = todaysDate.AddHours(hours).AddMinutes(minutes).AddSeconds(seconds).TimeOfDay; ;
}
private void TimerAction1(object e)
{
//some Code
}
}
this is design Code
partial class ASMSService
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
//
// ASMSService
//
this.ServiceName = "ASMSService";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
#endregion
private System.Diagnostics.EventLog eventLog1;
}
this is Program class:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ASMSService()
};
ServiceBase.Run(ServicesToRun);
}
}
I have read similar posts on this ..Some posts suggest to install microsoft Patch ..Other suggest the object created should be disposed properly ..I also tried to do that in Onstop method..But it is not working ..Some posts suggest that ServiceBase.Run() method should be called in Main() method ...it is also present in My code
Please Suggest

I can see one great problem with the ASMSService's timer:
It is created :
myTimer = new System.Threading.Timer(new TimerCallback(TimerAction1));
But it is never started:
private void SetTimer(int hours, int minutes, int seconds)
{
todaysDate = DateTime.Today;
previousDate = todaysDate.AddDays(-1);
setTime = todaysDate.AddHours(hours).AddMinutes(minutes).AddSeconds(seconds).TimeOfDay; ;
// You have set the setTime field, otherwise the timer will still have the infinite dueTime and interval - it is not running at all
// You should call SetChange method to start it.
this.mytimer.SetChange(0, (Int64)setTime.ToMilliseconds());
}
SetChange method is required to start the timer if you use the simplest constructor
You may also want to read the following links, they are dealing with similar situations and provide few insights to consider:
Windows service with timer
System.Threading.Timer Not Starting?

Related

How can I setup multiples Windows Services?

So, I was creating a windows service and i was following this video to setup the windows service.
https://www.youtube.com/watch?v=tAF9krJu3cs
So, I have a Model, I get the Model in the controller so I can build what I want to send, then, I call that Controller on the Service. After that, I created the Installer. Problem: I have 3 and i was able to create them adding: [RunInstaller(true)] in the beggining of every service. After that, I was saying that they were not manual and "prepraring" them for the errors, starting them, and, after that I started them. But, I turned on one of them, the other turns off, and so on. I was able to turn the 3 on after a while (maybe this was a bug) but they all stopped working again..... My code:
ProjectInstaller:
enter image description here
ProjectInstaller.Designer.cs :
{
partial class ProjectInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.AccountService = new System.ServiceProcess.ServiceInstaller();
this.FinInfoPrevYearService = new System.ServiceProcess.ServiceInstaller();
this.GetFinancialInfoService = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
//
// AccountService
//
this.AccountService.ServiceName = "AccountService";
this.AccountService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.AccountService_AfterInstall);
//
// FinInfoPrevYearService
//
this.FinInfoPrevYearService.ServiceName = "FinInfoPrevYearService";
this.FinInfoPrevYearService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.FinInfoPrevYearService_AfterInstall);
//
// GetFinancialInfoService
//
this.GetFinancialInfoService.ServiceName = "GetFinancialInfoService";
this.GetFinancialInfoService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.GetFinancialInfoService_AfterInstall);
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.AccountService,
this.FinInfoPrevYearService,
this.GetFinancialInfoService});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller AccountService;
private System.ServiceProcess.ServiceInstaller FinInfoPrevYearService;
private System.ServiceProcess.ServiceInstaller GetFinancialInfoService;
}
}
ProjectInstaller.cs:
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
}
private void AccountService_AfterInstall(object sender, InstallEventArgs e)
{
}
private void GetFinancialInfoService_AfterInstall(object sender, InstallEventArgs e)
{
}
private void FinInfoPrevYearService_AfterInstall(object sender, InstallEventArgs e)
{
}
}
}
One of the services:
enter image description here
Please help me guys.. I dont know what to do anymore...

Is System.Diagnostics.EventLog leaking memory?

When I run the following code :
static void Main(string[] args)
{
if (!System.Diagnostics.EventLog.SourceExists("eventSource"))
{
System.Diagnostics.EventLog.CreateEventSource("eventSource", "");
}
System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
eventLog.Source = "eventSource";
eventLog.Log = "";
for (int i = 0; i < 10000; i++)
{
Thread.Sleep(100);
eventLog.WriteEntry("test", EventLogEntryType.Information);
//I also tried the static method, the program still leaks
//System.Diagnostics.EventLog.WriteEntry("eventSource", "test", EventLogEntryType.Information);
}
Console.ReadKey();
}
The memory usage starts around 1MB, but rise up very quickly and doesn't stop. Why ?
The code I'm using to install windows service with a designated event log:
[RunInstaller(true)]
public partial class SampleServiceInstaller : System.Configuration.Install.Installer
{
private string SampleServiceName = string.Empty;
private string SampleLogName = string.Empty;
public SampleServiceInstaller()
{
this.SampleServiceName = "SampleService";
this.SampleLogName = this.SampleServiceName + "Log";
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Password = null;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
ServiceInstaller serviceInstaller = new ServiceInstaller();
//This must be identical to the WindowsService.ServiceBase name
// set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = this.SampleServiceName;
serviceInstaller.DisplayName = this.SampleServiceName;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.Description = "Sample Windows Service";
// kill the default event log installer
serviceInstaller.Installers.Clear();
// Create Event Source and Event Log    
// This recreates the log every time the service is reinstaled (old messages are lost)
if (EventLog.SourceExists(this.SampleServiceName)) EventLog.DeleteEventSource(this.SampleServiceName);
System.Diagnostics.EventLogInstaller logInstaller = new System.Diagnostics.EventLogInstaller();
logInstaller.Source = this.SampleServiceName; // use same as ServiceName
logInstaller.Log = this.SampleLogName; //can't be the same as service name
// Add all installers
this.Installers.AddRange(new Installer[] {
   serviceProcessInstaller, serviceInstaller, logInstaller
});
}
public override void Install(System.Collections.IDictionary savedState)
{
base.Install(savedState);
}
protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
{
base.OnBeforeUninstall(savedState);
}
service code:
public partial class SampleService : ServiceBase
{
/// <summary>
/// Designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Event log for the service
/// </summary>
EventLog serviceLog;
/// <summary>
/// Public Constructor for WindowsService.
/// - Initialization code here.
/// </summary>
public SampleService()
{
InitializeComponent();
}
/// <summary>
/// The Main Thread: list of services to run.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new SampleService() };
ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Startup code
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
base.OnStart(args);
//
// run your own start code here
//
serviceLog.WriteEntry("My service started", EventLogEntryType.Information, 0);
}
/// <summary>
/// Stop code
/// </summary>
protected override void OnStop()
{
//
// run your own stop code here
//
serviceLog.WriteEntry("My service stopped", EventLogEntryType.Information, 0);
base.OnStop();
}
/// <summary>
/// Cleanup code
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
//
// do disposing here
//
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Pause code
/// </summary>
protected override void OnPause()
{
base.OnPause();
//
// code to run if service pauses
//
}
/// <summary>
/// Continue code
/// </summary>
protected override void OnContinue()
{
base.OnContinue();
//
// code tu run when service continues after being paused
//
}
/// <summary>
/// Called when the System is shutting down
/// - when special handling
/// of code that deals with a system shutdown, such
/// as saving special data before shutdown is needed.
/// </summary>
protected override void OnShutdown()
{
//
// code tu run when system is shut down
//
base.OnShutdown();
}
/// <summary>
/// If sending a command to the service is needed
/// without the need for Remoting or Sockets,
/// this method is used to do custom methods.
/// int command = 128; //Some Arbitrary number between 128 & 256
/// ServiceController sc = new ServiceController("NameOfService");
/// sc.ExecuteCommand(command);
/// </summary>
/// <param name="command">Arbitrary Integer between 128 & 256</param>
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
//
// handle custom code here
//
}
/// <summary>
/// Useful for detecting power status changes,
/// such as going into Suspend mode or Low Battery for laptops.
/// </summary>
/// <param name="powerStatus">The Power Broadcast Status
/// (BatteryLow, Suspend, etc.)</param>
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
//
// handle power events here
//
return base.OnPowerEvent(powerStatus);
}
/// <summary>
/// To handle a change event
/// from a Terminal Server session.
/// Useful if determining
/// when a user logs in remotely or logs off,
/// or when someone logs into the console is needed.
/// </summary>
/// <param name="changeDescription">The Session Change
/// Event that occured.</param>
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
//
// handle session change here
//
base.OnSessionChange(changeDescription);
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
// first 8 letters should be unique
this.ServiceName = "SampleService";
// if you want to log service event to log registered while installing the service
string newLogName = this.ServiceName + "Log";
string newSourceName = this.ServiceName;
if (!EventLog.SourceExists(newSourceName))
{
EventLog.CreateEventSource(newSourceName, newLogName);
}
serviceLog = new EventLog();
serviceLog.Source = newSourceName;
serviceLog.Log = newLogName;
// Causes log to be disposed when the service is disposed
components.Add(serviceLog);
// Flags set whether or not to handle that specific type of event.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
}

Windows Service- Can it run two separate tasks scheduled at different intervals

I have written a Windows Service which triggers email ONCE in a WEEK at specific time. The service runs perfectly fine. Code is shown below:
protected override void OnStart(string[] args)
{
this.Log("Simple Service Started");
this.ScheduleService();
}
protected override void OnStop()
{
this.Log("Simple Service Stopped");
this.Schedular.Dispose();
}
private Timer Schedular;
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(SchedularCallback));
// Code that schedules the Callback
}
}
private void SchedularCallback(object e)
{
try
{
// Scheduled Job code
}
}
Now I have another similar requirement where I have to trigger another email, but its schedule has to be ONCE in 2 WEEKS. Is there a way this job can be accommodated in the same service, or I have to write another service?
I once did a similar design in one of my projects.
Try having a base abstract "ScheduledTask" class that defines your timing behavior, and have it used by inherited tasks classes.
Here is what I did for timers, I think there's only little work to change it to a Scheduler.
internal abstract class TaskBase
{
/// <summary>
/// Task timer
/// </summary>
private readonly Timer _timer;
/// <summary>
/// Set refresh time
/// </summary>
protected int TimeRefreshSec { get; private set; }
/// <summary>
/// Loop of timePassed
/// </summary>
protected int TimePassed { get; private set; }
protected TaskBase(double refreshInterval)
{
TimeRefreshSec = (int) refreshInterval / 1000;
TimePassed = 0;
_timer = new Timer(refreshInterval) { AutoReset = true };
_timer.Elapsed += Tick;
}
private void Tick(object sender, ElapsedEventArgs e)
{
TimePassed += TimeRefreshSec;
Tick();
}
public void Start()
{
ResetTimer();
// Run the task once when starting instead of waiting for a full interval.
Tick();
OnStart();
}
public void Stop()
{
if (_timer.Enabled)
{
_timer.Stop();
OnStop();
}
}
protected virtual void ResetTimer()
{
TimePassed = 0;
if (_timer.Enabled) _timer.Stop();
_timer.Start();
}
/// <summary>
/// Implement here a specific behavior when task is stopped.
/// </summary>
protected abstract void OnStop();
/// <summary>
/// Implement here a specific behavior when task is started.
/// </summary>
protected abstract void OnStart();
/// <summary>
/// This method is executed each time the task's timer has reached the interval specified in the constructor.
/// Time counters are automatically updated.
/// </summary>
protected abstract void Tick();
}
and for the service :
public partial class MyService : ServiceBase
{
private readonly List<TaskBase> _tasks;
public MyService()
{
InitializeComponent();
// Add in this list the tasks to run periodically.
// Tasks frequencies are set in the corresponding classes.
_tasks = new List<TaskBase>
{
new InheritingTask(),
new OherInheritingTask()
};
}
protected override void OnStart(string[] args)
{
try
{
_tasks.ForEach(t => t.Start());
}
catch (Exception ex)
{
Stop();
}
}
protected override void OnStop()
{
_tasks.ForEach(t => t.Stop());
}
}
EDIT:
The code for a class inheriting TaskBase:
class InheritingTask: TaskBase
{
public InheritingTask()
: base(Settings.Default.InheritingTaskInterval) // In milliseconds
{
//TODO: Custom initialization here
}
protected override void Tick()
{
//TODO: Task logic here
}
protected override void OnStart()
{ }
protected override void OnStop()
{ }
protected override void ResetTimer()
{
//TODO: Custom reset logic here
base.ResetTimer();
}
}
You could easily make a 2nd Schedular that is started in ScheduleService that is set to go off in two weeks however a Timer that fires once a week or two is a horrible way to do this, if the computer reboots you loose your timer and the email you where waiting on will not get sent.
You need a database of some kind to store when the next event should fire to survive restarts of your program, use a library that stores and does the scheduling for you like Hangfire.
Yes, you can achieve this using multithreading, for example via Tasks or Backgroundworkers. With this you can start each timer on a different thread which executes your operation when the timer ticks. It would also be advisable to separate timer and execution on different threads - for example Backgroundworkers for Timer 1 and 2 and Backgroundworkers for Execution 1 and 2.

Not getting OnStart event log entry in Windows Service

I have the following code for a windows service project. I have successfully built it and installed it. When I start it I get an event started in the event log. However, I never get the event for "In Onstart" any idea why this is going on?
namespace ADServiceCarlos
{
public partial class ADServiceCarlos : ServiceBase
{
public ADServiceCarlos()
{
InitializeComponent();
this.AutoLog = true;
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource","MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
}
}
}
OK, so this may solve your problem. It's hard to tell exactly without being able to see all your code, but read this - more specifically the "caution" part.
Do not use the constructor to perform processing that should be in
OnStart. Use OnStart to handle all initialization of your service. The
constructor is called when the application's executable runs, not when
the service runs. The executable runs before OnStart. When you
continue, for example, the constructor is not called again because the
SCM already holds the object in memory. If OnStop releases resources
allocated in the constructor rather than in OnStart, the needed
resources would not be created again the second time the service is
called.
So everything you are doing to initialise the event log in your constructor should be moved to the OnStart event. This will ensure it is create properly each time the service start, which means you should be able to log your OnStart event correctly (providing you do it after initialisation)
Based on what #musefan posted, here is an example. I had to move everything out of the constructor completely.
public class ServiceMain : System.ServiceProcess.ServiceBase
{
public const string SERVICE_NAME = "ServiceName";
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ServiceMain()
{
// This call is required by the Windows.Forms Component Designer.
InitializeComponent();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = SERVICE_NAME;
this.CanPauseAndContinue = true;
}
static void Main()
{
//Log all unhandled exceptions
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ServiceMain() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
//Do your stuff here
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Environment.Exit(1);
}
}

Windows Service Error 1053

I'm currently writing a windows service which connects to a crm system to pull down a schedule which then runs various datafeeds etc. I've got everything working except when I install everything and try to run start the service I get the following error :
"Error 1053: The service did not respond to the start or control request in a
timely fashion"
Here's the code I'm using in my Service1.cs;
namespace FeedManagementService
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// Instantiate the timer
Thread t = new Thread(new ThreadStart(this.InitTimer));
t.IsBackground = true;
t.Start();
} // OnStart
protected override void OnStop()
{
timer.Enabled = false;
} // OnStop
private void InitTimer()
{
timer = new System.Timers.Timer();
// Add the timer event
timer.Elapsed += new ElapsedEventHandler(timerTick);
// Set the interval
double timeInSeconds = 6.0;
timer.Interval = (timeInSeconds * 1000);
timer.Enabled = true;
} // InitTimer()
private void timerTick(object sender, EventArgs e)
{
// CRM connection stuffhere
} // timerTick
}
}
Then the following in the Service1.Designer.cs
namespace FeedManagementService
{
partial class Service1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ServiceName = "Feed Management Service";
this.CanPauseAndContinue = true;
} // InitializeComponent()
#endregion
}
}
And lastly the following in ProjectInstaller.cs
namespace FeedManagementService
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
ServiceProcessInstaller process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
ServiceInstaller serviceAdmin = new ServiceInstaller();
serviceAdmin.StartType = ServiceStartMode.Manual;
serviceAdmin.ServiceName = "Service1";
serviceAdmin.DisplayName = "Feed Management Service";
Installers.Add(process);
Installers.Add(serviceAdmin);
}
}
}
After a lot of investigation and fixing a whole bunch of "problems" which turned out to be nothing to do with the issue, I discovered that I needed the following in the Main() method of the service;
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
As a result of adding this everything seems to work perfectly now, the service starts as expected.
It seems you OnStart() method is not returnig within the allowed timeout. Does the message appears at once, or does it take some 30 seconds to show up? Does your CRM Connection Stuff(tm) takes a while to run?
A longshot: do you use any Windows.Forms stuff in your app? These should not be used on a service, and can interact in strange and mysterious ways.
I encountered the same issue and was not at all sure how to resolve it. Yes this occurs because an exception is being thrown from the service, but there are a few general guidelines that you can follow to correct this:
Check that you have written the correct code to start the service:
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new WinsowsServiceToRun()
};
ServiceBase.Run(ServicesToRun);
You need to ensure that there is some kind of infinite loop running in the class WinsowsServiceToRun
Finally, there may be some code which is not logging anything and closing the program abruptly (which was the case with me), in this case you will have to follow the old school of debugging which needed to write a line to a source (text/db/wherever). What I faced was that since the account running the service was not "Admin", the code was just falling off and not logging any exceptions in case it was trying to write to "Windows Event Log" even though the code was there to log exceptions. Admin privilege is actually not needed for logging to Even Log but it is needed to define the source. In case source of the event is not already defined in the system and the service tries to log it for the first time without admin privilege it fails. To solve this follow below steps:
Open command prompt with admin privilege
Paste the command : eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO <> /D "<>"
Press enter
Now start the service

Categories