【发布时间】:2018-03-13 10:45:51
【问题描述】:
我有一个用于从 TCP 套接字读取的线程;我从服务器收到一条消息以执行自动更新。所以,现在读取线程必须调用 servicebase Stop() 来触发 OnStop() 函数。然而,读取线程必须加入主线程才能正确终止服务。所以现在OnStop() 函数正在等待读取线程加入,但读取线程无法加入,因为它正在等待 Stop() 函数完成运行。
所以基本上它看起来像这样:
public void Start()
{
OnStart(new string[0]);
}
protected override void OnStart(string[] args)
{
stopEventRecv = new AutoResetEvent(false);
RecvThread = new Thread(RecvLoop);
RecvThread.Start();
}
protected override void OnStop()
{
// Doesn't matter because we are about to deadlock
stopEventRecv.Set();
// Dead lock
RecvThread.Join();
}
private void RecvLoop(object arg)
{
while (true)
{
if (stopEventRecv.WaitOne(5000))
{
return;
}
if (!IsConnected())
continue;
// here we get message from server saying to Stop so
// the message is processed and uses a callback where
// ServiceBase.Stop() is called.
// The reason for the callback isn't relevant to the
// question I don't think but i'm mentioning it in case.
// For the sake of the question I'll just call Stop()
// here to demonstrate the problem.
Stop();
}
}
我该如何解决这个问题?退出服务前是否需要加入所有线程?在这里 Abort 可以代替加入吗?
【问题讨论】:
-
我刚刚测试了 servicecontroller.stop,它似乎可以工作。
-
@Damien_The_Unbeliever 是的,你是对的,我错过了它确实只等待依赖服务。
标签: c# .net multithreading service