C# .NET - Windows Service needs to restart to keep its functioning

Asked By Xor Power on 05-Apr-11 01:33 AM
Hi,

I have created a windows service that sends email reminders every 30 seconds. 10 days before it was working fine but now it doesn't run until it is restarted manually from services.msc

Once it is restarted, the service then sends email.

The window service is written in C# and in Visual Studio 2005.

Let me know if any info needed.

Thanks for your inputs!
Reena Jain replied to Xor Power on 05-Apr-11 02:48 AM
hi,

Check out this simple code to Restart service using c# code;


public static void RestartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
  int millisec1 = Environment.TickCount;
  TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
 
  service.Stop();
  service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
 
  // count the rest of the timeout
  int millisec2 = Environment.TickCount;
  timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
 
  service.Start();
  service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
  //
  }
}

Hope this will help you
Reena Jain replied to Xor Power on 05-Apr-11 02:53 AM
hi,

Check this link for more help

http://www.aspcode.net/Creating-a-Windows-service-in-C.aspx