- C# code
-
CREATE TABLE [dbo].[MyServiceLog] ( [in_LogId] [int] IDENTITY (1, 1) NOT NULL, [vc_Status] [nvarchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [dt_Created] [datetime] NOT NULL ) ON [PRIMARY]
- C# code
-
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.ServiceProcess; namespace CodeGuru.MyWindowsService { public class MyService : System.ServiceProcess.ServiceBase { private System.Timers.Timer timer1; /// <remarks> /// Required designer variable. /// </remarks> private System.ComponentModel.Container components = null; public MyService() { // This call is required by the Windows.Forms // Component Designer. InitializeComponent(); } // The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.timer1 = new System.Timers.Timer(); ((System.ComponentModel.ISupportInitialize) (this.timer1)).BeginInit(); // // timer1 // this.timer1.Interval = 30000; this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed); // // MyService // this.ServiceName = "My Sample Service"; ((System.ComponentModel.ISupportInitialize) (this.timer1)).EndInit(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Set things in motion so your service can do its work. /// </summary> protected override void OnStart(string[] args) { this.timer1.Enabled = true; this.LogMessage("Service Started"); } /// <summary> /// Stop this service. /// </summary> protected override void OnStop() { this.timer1.Enabled = false; this.LogMessage("Service Stopped"); } /* * Respond to the Elapsed event of the timer control */ private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.LogMessage("Service Running"); } /* * Log specified message to database */ private void LogMessage(string Message) { SqlConnection connection = null; SqlCommand command = null; try { connection = new SqlConnection( "Server=localhost;Database=SampleDatabase;Integrated Security=false;User Id=sa;Password=;"); command = new SqlCommand( "INSERT INTO MyServiceLog (vc_Status, dt_Created) VALUES ('" + Message + "',getdate())", connection); connection.Open(); int numrows = command.ExecuteNonQuery(); } catch( Exception ex ) { System.Diagnostics.Debug.WriteLine(ex.Message); } finally { command.Dispose(); connection.Dispose(); } } } }
- C# code
-
using System; using System.Collections; using System.ComponentModel; using System.Configuration.Install; namespace CodeGuru.MyWindowsService { /// <summary> /// Summary description for ProjectInstaller. /// </summary> [RunInstaller(true)] public class ProjectInstaller : System.Configuration.Install.Installer { private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ProjectInstaller() { // This call is required by the Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.ServiceName = "My Sample Service"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] {this.serviceProcessInstaller1, this.serviceInstaller1}); } #endregion } }
-
用InstallUtil安装Windows服务 现在这个服务已经生成,你需要把它安装好才能使用。下面操作会指导你安装你的新服务。 1. 打开Visual Studio .NET命令提示 2. 改变路径到你项目所在的bin/Debug文件夹位置(如果你以Release模式编译则在bin/Release文件夹) 3. 执行命令“InstallUtil.exe MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。 4. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台 5. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了 6. 右击你的服务选择启动就可以启动你的服务了 在每次需要修改Windows服务时,这就会要求你卸载和重新安装这个服务。不过要注意在卸载这个服务前,最好确保服务管理控制台已经关闭,这会是一个很好的习惯。如果没有这样操作的话,你可能在卸载和重安装Windows服务时会遇到麻烦。仅卸载服务的话,可以执行相的InstallUtil命令用于注销服务,不过要在后面加一个/u命令开关。 调试Windows服务 从另外的角度度看,调试Windows服务绝不同于一个普通的应用程序。调试Windows服务要求的步骤更多。服务不能象你对普通应用程序做的那样,只要简单地在开发环境下执行就可以调试了。服务必须首先被安装和启动,这一点在前面部分我们已经做到了。为了便于跟踪调试代码,一旦服务被启动,你就要用Visual Studio把运行的进程附加进来(attach)。记住,对你的Windows服务做的任何修改都要对这个服务进行卸载和重安装。 附加正在运行的Windows服务 为了调试程序,有些附加Windows服务的操作说明。这些操作假定你已经安装了这个Windows服务并且它正在运行。 1. 用Visual Studio装载这个项目 2. 点击“调试”菜单 3. 点击“进程”菜单 4. 确保 显示系统进程 被选 5. 在 可用进程 列表中,把进程定位于你的可执行文件名称上点击选中它 6. 点击 附加 按钮 7. 点击 确定 8. 点击 关闭 9. 在timer1_Elapsed方法里设置一个断点,然后等它执行 总结 现在你应该对Windows服务是什么,以及如何创建、安装和调试它们有一个粗略的认识了。Windows服务的额处的功能你可以自行研究。这些功能包括暂停(OnPause)和恢复(OnContinue)的能力。暂停和恢复的能力在默认情况下没有被启用,要通过Windows服务属性来设置。