C#/.NET:检测程序是作为服务还是作为控制台应用程序运行 [英] C#/.NET: Detect whether program is being run as a service or a console application

查看:36
本文介绍了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() 如果失败则弹出错误对话框,然后直接返回向程序发出错误信号.

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.

有什么想法吗?

推荐答案

Rasmus, 这是之前的问题.

从答案看来,最流行的方法是使用简单的命令行选项,或者尝试访问 try catch 块中的 Console 对象(在服务中,控制台未附加到进程并尝试访问它会抛出一个例外).

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).

或者,如果您在测试/调试服务时遇到问题,请将代码移动到单独的 dll 程序集中并创建单独的测试工具(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天全站免登陆