哪种语言最适合用于构建Windows服务?
在这种情况下,“最易”被定义为编写代码的最少量和进入该语言的最低门槛。
哪种语言最适合用于构建Windows服务?
在这种情况下,“最易”被定义为编写代码的最少量和进入该语言的最低门槛。
显而易见的是,如果你具备C/C++/Java背景,我认为C#提供了最低的入门点。
假设你正在使用Visual Studio 2008,你可以按照以下步骤操作:
false
以防止默认写入应用程序事件日志的事件(注意:我并不是说您不应记录服务事件;我只是更喜欢写入自己的事件日志而不是应用程序日志 - 请参见下面)true
true
,则还需要覆盖OnShutdown方法。我已经创建了一个示例,说明了这些函数的使用。using System.Diagnostics;
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
{
installer.Log = "ServiceExample"; // enter your event log name here
}
}
private EventLogInstaller FindInstaller(InstallerCollection installers)
{
foreach (Installer installer in installers)
{
if (installer is EventLogInstaller)
{
return (EventLogInstaller)installer;
}
EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
if (eventLogInstaller != null)
{
return eventLogInstaller;
}
}
return null;
}
}
现在,您可以构建您的项目以获取Windows服务可执行文件。要安装服务,请打开Visual Studio 2008命令提示符,并导航到可执行文件所在的Debug或Release目录。在命令提示符处,键入以下内容:InstallUtil ServiceExample.exe。这将在本地计算机上安装您的服务。要卸载它,请在命令提示符处键入以下内容:InstallUtil /u ServiceExample.exe
只要您的服务没有运行,您就可以对其进行更改和重新构建,即不必卸载服务即可对其进行更改。但是,只要服务正在运行,您将无法使用修复程序和增强程序覆盖可执行文件。
要查看您的服务效果,请打开ServiceExample.cs文件并进行以下更改:
using System.Diagnostics;
public partial class ServiceExample : ServiceBase
{
public ServiceExample()
{
// Uncomment this line to debug the service.
//Debugger.Break();
InitializeComponent();
// Ties the EventLog member of the ServiceBase base class to the
// ServiceExample event log created when the service was installed.
EventLog.Log = "ServiceExample";
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("The service was started successfully.", EventLogEntryType.Information);
}
protected override void OnStop()
{
EventLog.WriteEntry("The service was stopped successfully.", EventLogEntryType.Information);
}
protected override void OnShutdown()
{
EventLog.WriteEntry("The service was shutdown successfully", EventLogEntryType.Information);
}
}
一旦您运行了具有这些更改的服务,您可以查看事件查看器中的ServiceExample事件日志,并查看在那里记录的信息。
编辑: 如果您希望使用应用程序事件日志而不是自定义事件日志进行事件记录,只需不对ProjectInstaller.cs文件进行任何更改。此外,在ServiceExample构造函数中留空设置EventLog的Log属性的行。当您运行服务时,您的日志消息将出现在应用程序事件日志中。
不是要引发争端,但我已经“标准化”使用WiX来制作所有的部署包,除了做老式的COM互操作类型的东西,因为这需要很多工作才能正确安装。我渴望WiX团队开发启动器部分,使您可以将前提条件和主要MSI放入可下载的EXE文件中。他们将其列入3.5计划,所以我会耐心等待,并暂时使用WinZip自解压执行文件。
对我来说,我只尝试了几种方式,Visual Studio和C#是最简单的。
Visual Studio为框架做好了所有必要的服务管道设置,我发现从VB6、VB.NET和C迁移学习C#非常容易。
使用Visual C#,您可以在网络上找到最多的代码示例。 结合Visual Studio,创建基本的Windows服务轻而易举。 Visual Studio还可以轻松创建MSI安装程序包。
这将是我的选择。
使用Visual Studio服务类型项目,使用C#或VB.NET。
我个人更喜欢C#,但通常很容易理解生命周期并在所需阶段编写逻辑。
构建安装程序也非常容易。
using System.Linq;
,在 ProjectInstaller() 中只需这么写:EventLogInstaller installer = this.Installers.Cast<Installer>().FirstOrDefault( eli => eli is EventLogInstaller ) as EventLogInstaller; if( installer != null ) installer.Log = "ServiceExample";
这只是我的个人建议。 - Meloviz