创建一个组合命令行/ Windows服务的应用程序 [英] Create a combo command line / Windows service app
问题描述
什么是在C#中的最佳方式来建立一个实用的应用程序,可以通过命令行运行并产生一些输出(或写入文件),但可能是运行作为Windows服务,以及完成其工作在后台(如监控目录,或其他)。
What's the best way in C# to set up a utility app that can be run from the command line and produce some output (or write to a file), but that could be run as a Windows service as well to do its job in the background (e.g. monitoring a directory, or whatever).
我想写出code一次,可以任意调用它交互的PowerShell的或其他的CLI,但同时也找到一种方法来安装相同的EXE文件作为Windows服务,并有它自动运行。
I would like to write the code once and be able to either call it interactively from PowerShell or some other CLI, but at the same time also find a way to install the same EXE file as a Windows service and have it run unattended.
我能做到这一点?如果是的话:我怎么能做到这一点。
Can I do this? And if so: how can I do this?
推荐答案
当然可以。
要做到这一点是使用命令行参数的一种方法,说/控制台,告诉除了作为服务运行版的控制台版本:
One way to do it would be to use a command line param, say "/console", to tell the console version apart from the run as a service version:
- 创建一个Windows控制台应用程序,然后
- 在Program.cs中,更多的precisely的主要功能,你可以测试/控制台的presence参数
- 如果在/控制台是存在的,正常启动程序
- 如果该参数是不存在的,从ServiceBase的调用服务类
// Class that represents the Service version of your app
public class serviceSample : ServiceBase
{
protected override void OnStart(string[] args)
{
// Run the service version here
// NOTE: If you're task is long running as is with most
// services you should be invoking it on Worker Thread
// !!! don't take too long in this function !!!
base.OnStart(args);
}
protected override void OnStop()
{
// stop service code goes here
base.OnStop();
}
}
...
然后在Program.cs的:
Then in Program.cs:
static class Program
{
// The main entry point for the application.
static void Main(string[] args)
{
ServiceBase[] ServicesToRun;
if ((args.Length > 0) && (args[0] == "/console"))
{
// Run the console version here
}
else
{
ServicesToRun = new ServiceBase[] { new serviceSample () };
ServiceBase.Run(ServicesToRun);
}
}
}
这篇关于创建一个组合命令行/ Windows服务的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!