使用Taskkill停止Windows服务 [英] Stopping windows service with taskkill

查看:408
本文介绍了使用Taskkill停止Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用C#杀死Windows服务的帮助,现在要使用以下选项杀死Windows服务:

I need help to kill a windows service using C#, now to kill the service use the following option:

从cmd:

sc queryex ServiceName

发现服务的PID

taskkill /pid 1234(exemple) /f

推荐答案

为了便于阅读,但如果您理解我的意思,我将使用单独的方法IsServiceInstalled,IsServiceRunning,StopService ..etc将服务交互分为其自己的类.

For ease of reading but I would separate the services interactions into it's own class with separate methods IsServiceInstalled, IsServiceRunning, StopService ..etc if you get what I mean.

此外,通过停止服务,它应该已经终止了该进程,但是我还介绍了如何执行类似的操作.如果该服务无法停止,而您是通过终止进程来停止它,那么如果您无法正确访问该服务,我将查看该服务代码.

Also by stopping the service it should kill the process already but I included how you would do something like that as well. If the service won't stop and you are stopping it by killing the process, I would look at the service code if you have access to it wasn't built correctly.

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();
                        }
                    }
                }
            }
        }
    }
}

这篇关于使用Taskkill停止Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆