mar*_*c_s 13 .net c# command-line windows-services
在C#中设置可以从命令行运行并生成一些输出(或写入文件)的实用程序应用程序的最佳方法是什么,但这可以作为Windows服务运行,以便在后台执行其工作(例如监视目录,或其他).
我想编写一次代码并能够从PowerShell或其他一些CLI以交互方式调用它,但同时也找到了一种方法来安装与Windows服务相同的EXE文件并使其无人值守.
我可以这样做吗?如果是这样的话:我怎么能这样做?
Mik*_*scu 19
是的你可以.
一种方法是使用命令行参数,比如说"/ 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);
}
}
Run Code Online (Sandbox Code Playgroud)
}
-
您可以检查Environment.UserInteractive以查看我们是否处于交互模式,而不是args检查. (3认同)
| 归档时间: |
|
| 查看次数: |
9275 次 |
| 最近记录: |