How can I use C# to stop SQL Server?
6 Answers
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
{
// ...
}
}
1 Comment
Steve Townsend
+1 - this has the advantage that you know whether it worked or not, and when
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)
Comments
If you don't want to use ServiceController you can kill sqlservr process to kill the right process.
Process.GetProcesses().Where(x => x.ProcessName == "sqlservr").ToList().ForEach(x => x.Kill());
1 Comment
Wael Galal El Deen
You should add WaitForExit for each process. Code should be like this: Process.GetProcesses().Where(x => x.ProcessName == "sqlservr").ToList().ForEach(x => { x.Kill(); x.WaitForExit(); });
using System.Diagnostics;
public static bool StopProcess(string name)
{
try
{
var process = Process.GetProcesses().SingleOrDefault(p => p.ProcessName == name);
process.Kill()
process.WaitForExit();
return true;
}
catch (Exception)
{
//throw;
return false;
}
}
6 Comments
Steve Townsend
I would think unexpected
Kill is not a great idea for SQL Server integrity. Are you sure you would do it this way?Remus Rusanu
@Steve Townsend: if TerminateProcess triggered data corruption SQL Server would be out of business. This is why (almost) all RDBMSs use WAL: msdn.microsoft.com/en-us/library/ms186259.aspx Torn page protection additionally protects against power outages: msdn.microsoft.com/en-us/library/aa337560.aspx
Steve Townsend
@Remus, you are right but I still would not choose this method when clean service stop is available
sshow
@SteveTownsend it has been edited to use
WaitForExit(). I guess that should be a more pleasant halt.kartal
SingleOrDefault not found in c# ! is t require another using ?
|