+ Reply to Thread
Results 1 to 2 of 2

Thread: Start, Stop and Restart Windows Service

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    10

    Start, Stop and Restart Windows Service

    I would like to be able to start , stop and restart a service on windows using code , how can i do that ?

    Thanks.
    Last edited by sarah; 11-08-2012 at 11:33 PM.

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    22
    A) Start a Service
    Code:
    public static void StartService(string serviceName, int timeoutMilliseconds)
    {
      ServiceController service = new ServiceController(serviceName);
      try
      {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
    
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
      }
      catch
      {
        // Errors goes here
      }
    }
    B) Stop a Service
    Code:
    public static void StopService(string serviceName, int timeoutMilliseconds)
    {
      ServiceController service = new ServiceController(serviceName);
      try
      {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
    
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
      }
      catch
      {
        // Error goes here
      }
    }
    C) Restart a Service
    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
      {
        // Error goes here
      }
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts