在C#中设置一个实用程序应用程序的最佳方法是什么?该应用程序可以从命令行运行并生成一些输出(或写入文件),但也可以作为Windows服务运行以在后台完成其作业(例如,监视目录或其他操作)。
我想编写一次代码,既可以从PowerShell或其他CLI交互式调用它,同时也可以找到一种方法将同一EXE文件安装为Windows服务并使其无人值守运行。
我能做到这点吗?如果可以:如何做到这一点?
在C#中设置一个实用程序应用程序的最佳方法是什么?该应用程序可以从命令行运行并生成一些输出(或写入文件),但也可以作为Windows服务运行以在后台完成其作业(例如,监视目录或其他操作)。
我想编写一次代码,既可以从PowerShell或其他CLI交互式调用它,同时也可以找到一种方法将同一EXE文件安装为Windows服务并使其无人值守运行。
我能做到这点吗?如果可以:如何做到这一点?
是的,您可以这样做。
一种方法是使用命令行参数,比如 "/console",来区分控制台版本和作为服务运行的版本:
// 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 文件中:
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服务、命令行程序、ASP.NET Web服务、WCF服务等)。
可以做到。
您的启动类必须扩展ServiceBase。
您可以使用静态void Main(string [] args)启动方法来解析命令行开关以在控制台模式下运行。
类似以下内容:
static void Main(string[] args)
{
if ( args == "blah")
{
MyService();
}
else
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}