。C#/。NET:检测程序是否正在运行作为一种服务或一​​个控制台应用程序 [英] C#/.NET: Detect whether program is being run as a service or a console application

查看:164
本文介绍了。C#/。NET:检测程序是否正在运行作为一种服务或一​​个控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#/。NET程序,可以同时运行作为控制台应用程序,并作为一项服务。 目前,我给它一个命令行选项来启动一个控制台应用程序,但我想避免的。

I have a C#/.NET program that can run both as a console application and as a service. Currently I give it a command-line option to start as a console application, but I would like to avoid that.

是否有可能以编程方式检测我的程序是否被作为一种服务启动?

Is it possible to programmatically detect whether my program is being started as a service?

如果是纯粹的Win32,我可以尝试开始与StartServiceCtrlDispatcher服务,并回落到控制台如果它返回ERROR_FAILED_SERVICE_CONTROLLER_CONNECT,但如果失败,然后就返回,而不System.ServiceProcess.ServiceBase.Run()弹出一个errordialog发出错误信号给程序。

If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program.

任何想法?

推荐答案

拉斯穆斯,的这是较早的问题

这是问题的答案似乎是最流行的方法是使用一个简单的命令行选项,或尝试访问控制台对象在try catch块(在服务控制台没有连接到该进程,并试图访问它抛出一个例外)。

From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process and trying to access it throws an exception).

或者,如果您无法测试/调试服务,此举code到一个单独的DLL组件并创建一个seprate测试工具(的WinForms /控制台等)。

Or if you're having trouble testing/debugging the service, move code into a separate dll assembly and create a seprate test harness (winforms/console etc).

(只注意到乔纳森增加了解决问题的办法的结尾。)

(Just noticed that Jonathan has added his solution to the end of the question.)

这篇关于。C#/。NET:检测程序是否正在运行作为一种服务或一​​个控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆