且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#/.NET:检测程序是作为服务还是作为控制台应用程序运行

更新时间:2023-02-19 19:00:46

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