I just ran this code and it worked:
csharp Code:
using System;
using System.ServiceProcess;
using System.Threading;
public class Program
{
static void Main()
{
using var printSpoolerController = new ServiceController("Print Spooler");
if (printSpoolerController.Status == ServiceControllerStatus.Stopped)
{
printSpoolerController.Start();
for (var i = 0; i < 10; i++)
{
printSpoolerController.Refresh();
if (printSpoolerController.Status == ServiceControllerStatus.Running)
{
Console.WriteLine(i);
break;
}
Thread.Sleep(100);
}
}
Console.WriteLine(printSpoolerController.Status);
}
}
In my testing, it only took one Sleep call for the status of the service to change.
Note that I had to run the app as an admin or an exception was thrown.