我已经构建了一个应用程序来解析 Xml 文件以将数据集成到 mssql 数据库中。我正在使用 Visual C# Express。有一种方法可以使用 Express Edition 提供服务,还是我必须让 Visual Studio 来做?
最佳答案
当然可以。您甚至可以使用 csc
来完成。 VS 中唯一的东西就是模板。但您可以自己引用 System.ServiceProcess.dll。
要点:
- 编写一个继承自
ServiceBase
的类 - 在您的
Main()
中,使用ServiceBase.Run(yourService)
- 在
ServiceBase.OnStart
覆盖中,生成您需要完成工作的任何新线程等(Main()
需要立即退出,否则将被视为启动失败)
示例代码
非常基本的模板代码是:
程序.cs:
using System;
using System.ServiceProcess;
namespace Cron
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
System.ServiceProcess.ServiceBase.Run(new CronService());
}
}
}
CronService.cs:
using System;
using System.ServiceProcess;
namespace Cron
{
public class CronService : ServiceBase
{
public CronService()
{
this.ServiceName = "Cron";
this.CanStop = true;
this.CanPauseAndContinue = false;
this.AutoLog = true;
}
protected override void OnStart(string[] args)
{
// TODO: add startup stuff
}
protected override void OnStop()
{
// TODO: add shutdown stuff
}
}
}
CronInstaller.cs:
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
[RunInstaller(true)]
public class CronInstaller : Installer
{
private ServiceProcessInstaller processInstaller;
private ServiceInstaller serviceInstaller;
public CronInstaller()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = "Cron"; //must match CronService.ServiceName
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
.NET 服务应用程序的安装方式与普通服务应用程序不同(即您不能使用 cron.exe/install
或其他一些命令行参数。相反,您必须使用.NET SDK 的 InstallUtil
:
InstallUtil /LogToConsole=true cron.exe
资源
关于c# - 如何使用 Visual c# Express 制作服务应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569606/