C#使用Windows Service

时间:2023-03-10 01:35:00
C#使用Windows Service

前言:Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这种服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。

  • C#创建Windows服务的步骤:

1.创建Windows Service项目

从Visual C# 工程中选取 Windows 服务(Windows Service)选项,给工程一个新文件名,然后点击 确定。

2.向服务中函数功能实现

OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。在这里,当启动和停止服务时,向一个文本文件中写入一些文字信息,代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; namespace MyService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n"); sw.Flush();
sw.Close();
fs.Close();
} //protected override void OnContinue()
//{
// base.OnContinue();
//} //protected override void OnPause()
//{
// base.OnPause(); // father class method inherit
//} //protected override void OnShutdown()
//{
// base.OnShutdown();
//} protected override void OnStop()
{
FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WindowsService: Service Stopped" + DateTime.Now.ToString() + "\n");
sw.Flush();
sw.Close();
fs.Close(); }
}
}

 

4.回到设计窗口点右键选择-添加安装程序 -生成serviceInstaller1和 serviceProcessInstaller1两个组件 
把serviceInstaller1的属性ServiceName改写为你的服务程序名,并把启动模 式设置为AUTOMATIC  
把serviceProcessInstaller1的属性account改写为 LocalSystem

5.编译链接生成服务程序

通过从生成菜单中选择生成来生成项目。

6.安装服务

以管理员的身份运行cmd

C#使用Windows Service

7.卸载服务

用项目的输出作为参数,从命令行运行 InstallUtil.exe。

installutil /u yourproject.exe

C#使用Windows Service

你可以在代码编写当中,写入timer定时器,开启服务之后就可以在服务器端不停的跑代码了。例如执行sqlserver数据库存储过程。

C#使用Windows Service