关于windows:C-编写-Windows-服务应用程序

3次阅读

共计 1582 个字符,预计需要花费 4 分钟才能阅读完成。

在 .NET Framework 平台中编写 Windows 服务 算是一件比拟容易的事件。首先关上 Visual Studio 创立一个名为 Windows 服务 的我的项目,创立后看到的是一个 .cs 文件的设计界面,用鼠标右键单击能够看到几个菜单,点击增加安装程序后又会转到另一个 .cs 文件的设计界面,这个界面上默认有两个组件,一个叫 serviceProcessInstaller1,另一个叫 serviceInstaller1,其中 serviceInstaller1 组件的属性窗口如下:

Description 属性和 DisplayName 属性别离指服务的形容和名字,ServiceName 属性指服务的过程名字,StartType 属性指服务的启动类型,这里抉择 Automatic 的意思为主动启动;这里还会把 serviceProcessInstaller1 组件的 Account 属性批改为 LocalSystem,要不然等到装置服务的时候可能会呈现要求输出用户名和明码的对话框。

服务装置组件的配置曾经完了,当初转到服务的代码地位,还是在方才那个右键菜单地位,点击“查看代码”就能够看到服务要执行的代码,我编写如下代码:

using System;
using System.ServiceProcess;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {public Service1()
        {InitializeComponent();
        }
        System.Timers.Timer timer = new System.Timers.Timer();
        protected override void OnStart(string[] args)
        {
            timer.Interval = 1000;
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timertick);
        }
        private void timertick(object source, System.Timers.ElapsedEventArgs e)
        {System.IO.FileStream fs = new System.IO.FileStream("D:\\log.txt", System.IO.FileMode.Append);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString());
            sw.Close();
            fs.Close();}
        protected override void OnStop()
        {}}
}

OnStart 办法中的代码会在服务启动时执行一次,所以这里我用了一个定时器有限执行;OnStop 办法中的代码会在服务进行时执行。服务程序编译后仍然会是 .exe 文件,只不过不可能间接运行,这里须要应用 .NET Framework 提供的程序来装置咱们编写的服务,装置服务的命令如下:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\WindowsService1.exe

留神命令须要用管理员权限执行,InstallUtil 程序的门路可能会不一样,这个依据 .NET Framework 装置时的门路决定,卸载服务的命令如下:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u D:\WindowsService1.exe

服务装置胜利后能够在 Windows 服务管理程序中找到:

正文完
 0