Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

.net - Detect if code is running as a service

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 : (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 : (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...