如何使用Visual c#Express制作服务应用程序?
我已经构建了一个解析Xml文件的应用程序,用于在mssql数据库中集成数据。 我正在使用Visual c#express。 有一种方法可以使用快递版本进行服务,或者我必须让Visual Studio来完成它吗?
绝对可以。 你甚至可以用csc
来做。 VS中唯一的东西就是模板 。 但您可以自己引用System.ServiceProcess.dll。
关键点:
- 编写一个inheritance自
ServiceBase
的类 - 在你的
Main()
,使用ServiceBase.Run(yourService)
- 在
ServiceBase.OnStart
覆盖中,产生你需要做的任何新线程等(Main()
需要立即退出或者算作失败的开始)
示例代码
非常基本的模板代码是:
Program.cs :
using System; using System.ServiceProcess; namespace Cron { static class Program { /// /// The main entry point for the application. /// 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
资源
- 由Mark Strawmyer 在.NET中创建Windows服务
- Dave Fetterman 在五分钟内在.NET中编写一个有用的Windows服务
- 安装和卸载服务
- 演练:在组件设计器中创建Windows服务应用程序
您可以尝试使用Visual Web Developer Express以及用于Web服务的coding4fun开发人员工具包库(通过托管代码包装器): –
http://www.microsoft.com/express/samples/c4fdevkit/default.aspx
Express Edition可以编写和编译Windows服务项目,但它无法正常创建它们。 唯一简单的方法是在Visual Studio中创建一个新的服务项目,然后将项目文件复制到Express Edition的计算机上。 之后,您不再需要Visual Studio了。
有3种方法可以实现此目的:
- 使用Visual Studio转到计算机并创建项目
- Google是一个用于创建服务和下载项目源代码的在线教程
- 下载并安装Visual Studio的90天试用版以创建项目
但是,您仍然会遇到一些困难,例如,如果要重命名项目,或者不必为每个新服务重复此操作。 最好的长期解决方案是让老板最终支付标准版或专业版的副本。
根据这篇 MSDN文章,您没有服务的项目模板。 但我很确定如果您知道模板的function,您可以创建和编译服务。