如何停止Windows服务C#?

3

我的Windows服务在OnStart()方法中创建了1个线程。该线程的代码包含1个while循环,代码如下:

    Thread mworker;       
    AutoResetEvent mStop = new AutoResetEvent(false); 
     protected override void OnStart(string[] args)
{
    // TODO: Add code here to start your service.

    mworker = new Thread(pwd_fetch);
    mworker.IsBackground = false;
    mworker.Start();
}

protected override void OnStop()
{
    // TODO: Add code here to perform any tear-down necessary to stop your service.
    mStop.Set();
    mworker.Join();
}

private void pwd_fetch()
{
    while(true)
    {
        //some other code

        if (mStop.Set()==true)
            break;
    }
}

我希望while循环条件为真,但使用if()指令来停止循环时,仍无法停止服务。
有人知道原因吗?我该如何解决这个问题?

mStop是什么,Set是属性还是方法?如果它是方法,那么在每种情况下Set都会返回false。 - Romil Kumar Jain
请参考以下链接了解关于AutoresetEvent中的Set和WaitOne方法:http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.aspx - Romil Kumar Jain
5个回答

2
为停止服务,您需要调用servicecontroller实例并将其停止。
ServiceController service = new ServiceController("ServiceName");
service .Stop();

2
在您的线程循环方法中,您需要使用mStop.WaitOne(带有超时)。调用set将设置句柄...这不是您在此处想要做的事情。
 if (mStop.WaitOne(500))
     break;

我建议将Visual Studio调试器附加到正在运行的服务上。在OnStop()和pwd_fetch()例程中设置断点,以查看发生了什么。尝试停止服务并查看哪些断点被触发以及发生了什么。这应该能解决问题。 - pilotcam
在 mStop.Set() 指令之后,断点进入了 mworker.join()。但是断点从未进入 pwd_fetch()。 - sailer
只是猜测:也许有其他东西正在重置您的mStop?它是一个AutoResetEvent..任何等待(或重置)都会这样做并防止您的循环退出。在这种情况下,手动重置事件可能是更安全的选择。除此之外,我只能建议您使用调试器继续通过线程循环,并查看被命中的内容。 - pilotcam

0
如果您想让服务自行停止,只需调用以下命令:
this.Stop()

0

你必须在服务启动事件中添加线程代码,而不是在启动时添加。


0

1. 在 while 循环中,使用布尔变量代替始终为 "true" 的条件。这样,您可以在需要终止循环内代码的位置将其设置为 false。

2. 调用 mworker.Abort() 方法来停止线程。

3. 停止服务的方法如下:

new ServiceController("ServiceName").Stop();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接