在 WCF 托管服务中加入线程
任何人都可以推荐一种“干净”的方式来关闭托管在 servicehost 对象中的 WCF 服务及其线程吗?
调用servicehost.Close();当服务产生其他线程时不起作用:/
干杯,
Rob
Can anyone recommend a "clean" way of closing a WCF service and its threads when hosted in a servicehost object?
Calling servicehost.Close(); doesn't work when the service has spawned other threads :/
Cheers,
Rob
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有服务本身及其生成的线程的协作,这确实是无法从外部安全地完成的事情。一种选择是让服务通过可以通过主机环境控制的特殊方式生成线程,并让这些线程进一步协作,以便可以干净地关闭它们。
例如,您可以有一个自定义线程池类,该类为每个线程生成一个事件的引用,该事件向其发出信号,表明它必须停止处理并关闭。 .NET 4.0 将通过任务库使这一切变得更简单,但同时您将必须自己完成。
另外,在这种情况下,如果要生成原始线程(而不是使用 CLR 线程池)将它们创建为后台线程,则应该小心。这可以帮助避免当您希望关闭进程时使其保持活动状态(尽管我仍然建议确保彻底关闭它们)。
That's really something you cannot do from the outside safely without collaboration from the service itself and the threads it spawned. One option would be to have the service spawn threads through special means that can be controlled through your host environment and have those threads furthermore collaborate so that they can be shutdown cleanly.
For example, you could have a custom thread pool class that gives each thread spawn a reference to an event that signals to it that it must stop processing and shutdown. .NET 4.0 is going to make this simpler with the Task Library, but meanwhile you're going to have to do it on your own.
Also, you should take care if you're spawning raw threads (instead of using the CLR thread pool) to create them as background threads in cases like this. This can help in avoiding keeping the process alive when you want it to shut down (though I'd still recommend making sure you shut them down cleanly).