[英]How to stop Windows service C#?
我的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循环条件为true,但要打破循环我正在使用if()指令,但仍然无法停止服务。
有谁知道,为什么会这样? 我怎么解决这个问题?
在线程循环方法中,您需要使用mStop.WaitOne(具有超时)。 调用set将设置句柄...这不是你想要做的。
if (mStop.WaitOne(500))
break;
要停止服务,您必须调用servicecontroller实例并将其停止
ServiceController service = new ServiceController("ServiceName");
service .Stop();
如果您希望服务自行停止,您只需致电:
this.Stop()
您必须在服务启动事件中添加线程代码,而不是在启动时添加。
1.在while循环中始终使用布尔变量而不是“true”然后您可以将其设置为false,您需要在循环内终止代码。
2.Call mworker.Abort()停止线程。
3.停止服务
new ServiceController("ServiceName").Stop();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.