Skip to content

Instantly share code, notes, and snippets.

@tommyready
Last active March 18, 2022 21:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommyready/552f2d177239d9acfda63d786596c29f to your computer and use it in GitHub Desktop.
Save tommyready/552f2d177239d9acfda63d786596c29f to your computer and use it in GitHub Desktop.
Using C# to Restart a Windows Service.
using System;
using System.ServiceProcess;
using System.Diagnostics;
namespace RestartService
{
class Program
{
static void Main(string[] args)
{
try
{
string serviceToRestart = args[0]; // Set Service Name
Console.WriteLine("Begining Restart of " + serviceToRestart);
RestartService(serviceToRestart, 60000); // Restart Service w/60 Seconds for Timeout
} catch (Exception e)
{
// Log Error Message
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "RestartServiceConsole";
eventLog.WriteEntry(e.Message, EventLogEntryType.Error, 101, 1);
}
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
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();
Console.WriteLine("Stopping " + serviceName + ".............");
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
Console.WriteLine("Starting " + serviceName + ".............");
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
} catch( Exception e )
{
// Log Error Message
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "RestartServiceConsole";
eventLog.WriteEntry(e.Message, EventLogEntryType.Error, 101, 1);
}
Console.WriteLine("Error Restarting " + serviceName);
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment