C# を使用して Windows サービスを強制終了するには、次のオプションを使用してサービスを強制終了する必要があります。
コマンドから:
sc queryex ServiceName
PID
サービスの を発見した後
taskkill /pid 1234(exemple) /f
読みやすくするために、IsServiceInstalled、IsServiceRunning、StopService などの個別のメソッドを使用して、サービスの相互作用を独自のクラスに分離します。
また、サービスを停止することで、すでにプロセスを強制終了する必要がありますが、そのようなことを行う方法も含めました。サービスが停止せず、プロセスを強制終了して停止している場合、アクセスできるサービスコードが正しく構築されていないかどうかを確認します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals("MyServiceNameHere"));
if (sc != null)
{
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();
Process[] procs = Process.GetProcessesByName("MyProcessName");
if (procs.Length > 0)
{
foreach (Process proc in procs)
{
//do other stuff if you need to find out if this is the correct proc instance if you have more than one
proc.Kill();
}
}
}
}
}
}
}
プロセス ID がわかっている場合は、Process.GetProcessById(Id).Kill(); を使用します。プロセス名がわかっている場合は、Process.GetProcessesByName(name).Kill(); を使用します。