How can I use C# to stop SQL Server?
+2
A:
Try stopping the service.
using System.ServiceProcess;
...
ServiceController controller = new ServiceController();
controller.MachineName = ".";
controller.ServiceName = "MySqlServerInstance";
controller.Stop();
Wix
2010-10-06 17:10:42
+10
A:
From http://www.csharp-examples.net/restart-windows-service/
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
{
// ...
}
}
RedFilter
2010-10-06 17:10:44
+1 - this has the advantage that you know whether it worked or not, and when
Steve Townsend
2010-10-06 17:13:18
A:
using System.Diagnostics;
public static bool StopProcess(string name)
{
try
{
var process = Process.GetProcesses().SingleOrDefault(p => p.ProcessName == name);
process.WaitForExit();
return true;
}
catch (Exception)
{
//throw;
return false;
}
}
sshow
2010-10-06 17:13:38
I would think unexpected `Kill` is not a great idea for SQL Server integrity. Are you sure you would do it this way?
Steve Townsend
2010-10-06 17:20:18
@Steve Townsend: if TerminateProcess triggered data corruption SQL Server would be out of business. This is why (almost) all RDBMSs use WAL: http://msdn.microsoft.com/en-us/library/ms186259.aspx Torn page protection additionally protects against power outages: http://msdn.microsoft.com/en-us/library/aa337560.aspx
Remus Rusanu
2010-10-06 19:46:16
@Remus, you are right but I still would not choose this method when clean service stop is available
Steve Townsend
2010-10-06 20:02:23
@SteveTownsend it has been edited to use `WaitForExit()`. I guess that should be a more pleasant halt.
sshow
2010-10-06 20:20:47
+4
A:
Execute from a SqlCommand: SHUTDOWN WITH NOWAIT;
. The advantages over the other proposed solutions:
- this requires DB priviledges (sysadmin/serveradmin), not OS privileges
- works over any network firewall as long as T-SQL is let in (no extra ports needed)
- you don't need to figure out the service name (MSSQL$instancename)
- works if the service is started from console (
sqlservr -c
, not service start)
Remus Rusanu
2010-10-06 19:07:26