检测,如果code是作为服务运行code

2023-09-04 00:32:19 作者:思念苦无药

有没有办法为.NET库,以检测是否被作为服务运行?

Is there a way for an .NET library to detect whether or not it is being run as a service?

我的图书馆可以运行两种方式。但是,当它作为服务运行,开发人员需要调用的另一种方法,表明事实或某些功能将无法正常工作。我想我的图书馆,它处理日志,写一个警告,如果它被用在一个服务,而不被调用该方法。

My library can be run either way. But when its run as a service, developers need to call an additional method indicating that fact or certain features won't work correctly. I want my library, which handles logging, to write a warning if it is used in a service without that method being called.

推荐答案

在通过智能感知,调试器和文档一番搜索,我们无法找到任何严格可靠。它可能会获得当前进程ID,并尝试找出如果这一进程注册与SCM,但在.NET提供了一种方式来获得所有服务的集合,它们的进程ID并不在现有的资料。进程名比较来服务名是可能的,但不一定是可靠的。

After much searching through intellisense, the debugger, and documentation we weren't able to find anything strictly reliable. It may be possible to get the current process Id and try to find out if that process is registered with the SCM, but while .NET provides a way to get a collection of all the services, their process Ids are not among the information available. Comparing the process name to service names is possible but not necessarily reliable.

不过,有两件事情是比较容易检查并可满足您需要的区别,如果不完全这是code作为服务运行?

However, there are two things that are relatively easy to check and may suffice for the distinction you need, if not exactly "Is this code running as a service?"

System.Environment.UserInteractive :(斯蒂芬·马丁指出的)。如果这是真的,它不能是一个服务。大多数的过程而不是一种服务(也不是设备驱动程序)会说真。一些控制台应用程序可能会说假以非交互的情况下,如构建过程的一部分运行时。

System.Environment.UserInteractive : (as Stephen Martin noted) If this is true, it can't be a service. Most processes which are not a service (nor a device driver) will say true. Some console apps may say false when run in non-interactive circumstances such as part of a build process.

System.Diagnostics程序。 Process.GetCurrentProcess ()。的SessionID :(我认为这是同样的事情皮埃尔越来越AT)如果不为0,它不是作为服务启动。大多数的普通应用程序将无法在会话0(有一些不那么正常的异常所指出的皮埃尔和斯蒂芬)。最大的问题是如何表现的较旧的操作系统,如XP或之前下。 XP和Windows 2000显然有服务会话0运行,但正常的应用程序将在会话0为好。 XP的一些配置(域中例如不能)允许多个用户会话的同时,他们各自得到了不同的会话ID,但第一个检查Vista之前获取会话0,所以它不是有效的。

System.Diagnostics.Process.GetCurrentProcess().SessionId : (which I think is the same thing Pierre was getting at) If this is not 0, it was not started as a service. Most normal applications will not be in session 0 (with some not-so-normal exceptions as noted by Pierre and Stephen). The biggest question is how this behaves under an older OS such as XP or before. XP and Windows 2000 apparently have services running in session 0, but normal applications will be in session 0 as well. Some configurations of XP (eg. not in a domain) allow multiple user sessions at the same time and they each get a different session id, but the first one gets session 0. So it's not as effective a check prior to Vista.

所以,这取决于你的实际需要来区分,一个或两个检查可能为你工作。

So, depending on what you actually need to distinguish, one or both of these checks might work for you.