How to detect if Topshelf is running in console mode

你离开我真会死。 提交于 2020-01-01 08:38:56

问题


I am using Topshelf combined with FluentSchedule for a Windows Service.

However, I want to be able to trial-run the application to simply start up and not execute the FluentSchedule code that sets up the timer etc.

Is there a way when running the exe file from the Command Line (i.e. without 'install' command) to check from TopShelf that it is running in Console mode?


回答1:


It's sort of a hack, but you can try to cast the HostControl interface to ConsoleRunHost, and if it's that type, you're running as a console application.

It's not ideal, sure, but surely you can hide this in an extension method to make it less ugly.

public static bool IsRunningAsConsole(this HostControl control)
{
    return control is ConsoleRunHost;
}

And you then get access to the HostControl by passing it in through the call to WhenStarted() in your service configuration.

s.WhenStarted((tc, hostControl) => tc.Start(hostControl));



回答2:


You can use Environment.UserInteractive . Technically this won't work in 100% of the cases as it is possible to run a service in user-interactive mode, but this is a fringe case.



来源:https://stackoverflow.com/questions/28740658/how-to-detect-if-topshelf-is-running-in-console-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!