使用 C# 开发和安装 Windows 服务

作者 : 慕源网 本文共4640个字,预计阅读时间需要12分钟 发布时间: 2022-03-12 共474人阅读

什么是 Windows 服务

  • 使您能够创建在其自己的 Windows 会话中运行的长时间运行的可执行应用程序。
  • 可以在计算机启动时自动启动,无需任何用户交互即可暂停和重新启动。
  • 通过运行命令行实用程序 InstallUtil.exe 并将路径传递到服务的可执行文件,可以轻松安装。

为什么是 Windows 服务?

一些企业最常见的要求之一是基于某个时间间隔的长时间运行的计划作业。例如:每天下午发送一份时事通讯或每隔一小时向客户发送一封电子邮件提醒。

因此,构建 Windows 服务可能是实现目标的可靠解决方案之一,该目标可以在幕后完成所需工作,而不会干扰同一台计算机上的其他用户。

强烈推荐

海量程序代码,编程资源,无论你是小白还是大神研究借鉴别人优秀的源码产品学习成熟的专业技术强势助力帮你提高技能与技能。在此处获取,给你一个全面升级的机会。只有你更值钱,才能更赚钱

海量源码程序,学习别人的产品设计思维与技术实践

介绍

本文介绍了开发和安装 Windows 服务以执行基于时间间隔的计划作业的分步过程。

打开 Visual Studio 并从菜单中选择“文件”->“新建”->“项目…”。

将打开一个新项目窗口。选择“Visual C#”>>“Windows”项目类型并从右侧选择“Windows Service”并将项目命名为“TestWindowsService”,如下面的截图所示。

单击“确定”后,将创建项目,您将看到服务的设计视图,如下面的屏幕所示。右键单击解决方案资源管理器中的“Service1.cs”文件并将其重命名为“调度程序”或您要为其提供的任何其他名称。然后单击“单击此处切换到代码视图”。

在代码视图中,您可以看到两个方法称为 OnStart() 和 OnStop()。OnStart() 在 Windows 服务启动时触发,而 OnStop() 在服务停止时触发。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace TestWindowService
{
    public partial class Scheduler : ServiceBase
    {
        public Scheduler()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {

        }
        protected override void OnStop()
        {

        }
    }
}

右键单击TestWindowService 项目,添加一个新类并将其命名为“Library.cs”。这个类将有助于创建我们在项目中需要的方法。如果您的 TestWindowService 是一个大项目,您可以创建一个 ClassLibrary 项目并将其引用到您的 TestWindowService。

Library.cs

将类公开并将其声明为静态类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TestWindowService
{
    public static class Library
    {

    }
}

创建一个日志方法 (WriteErrorLog) 来记录异常。

public static void WriteErrorLog(Exception ex)
{
    StreamWriter sw = null;
    try
    {
        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
        sw.Flush();
        sw.Close();
    }
    catch
    {
    }
}

再创建一种日志方法 (WriteErrorLog) 来记录自定义消息。

public static void WriteErrorLog(string Message)
{
    StreamWriter sw = null;
    try
    {
        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
        sw.Flush();
        sw.Close();
    }
    catch
    {
    }
}

Scheduler.cs

现在返回到我们的 Scheduler.cs 文件并声明一个 Timer。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace TestWindowService
{
    public partial class Scheduler : ServiceBase
    {
        private Timer timer1 = null;

        public Scheduler()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
        }
        protected override void OnStop()
        {
        }
    }
}

在 OnStart() 方法和 timer1_Tick() 中编写以下代码:

protected override void OnStart(string[] args)
{
    timer1 = new Timer();
    this.timer1.Interval = 30000; //every 30 secs
    this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    timer1.Enabled = true;
    Library.WriteErrorLog("Test window service started");
}

private void timer1_Tick(object sender, ElapsedEventArgs e)
{
    //Write code here to do some job depends on your requirement
    Library.WriteErrorLog("Timer ticked and some job has been done successfully");
}

在 OnStop() 方法中编写以下代码:

protected override void OnStop()
{
    timer1.Enabled = false;
    Library.WriteErrorLog("Test window service stopped");
}

Scheduler.cs [Design]

现在返回到 Scheduler.cs [Design] 并右键单击编辑器窗口,然后单击“添加安装程序”。

然后你可以看到会有一个名为“ProjectInstaller.cs”的新文件,如下所示。

右键单击“serviceInstaller1”,然后单击“属性”。

将 ServiceName 更改为“Test Windows Service”(或您自己的名称)并将 StartType 更改为“Manual”(或者如果您需要此服务是自动的,您可以选择“Automatic”)。

右键单击 serviceProcessInstaller1,转到属性窗口并将“帐户”更改为“本地系统”。

构建项目以在您创建解决方案的位置查看 .exe 文件。

就这样。您的 Windows 服务已准备好安装在您的机器上。

安装 Windows 服务

转到“开始”>>“所有程序”>>“Microsoft Visual Studio 2012”>>“Visual Studio 工具”,然后单击“VS2012 的开发人员命令提示符”。

键入以下命令:

cd <TestWindowService.exe 文件的物理位置>

就我而言,它是:

cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug

接下来键入以下命令:

InstallUtil.exe “TestWindowService.exe”

并按 Enter。

到这里,TestWindowService 安装成功。

如何启动 Windows 服务

由于我们选择了 StartType = Manual,我们必须通过访问计算机中的“服务和应用程序”窗口手动启动 Windows 服务。

选择Test Windows Service,点击“Start”启动服务。转到“TestWindowService.exe”位置查看日志。

LogFile.txt

由于我们通过将一些日志写入一个名为 LogFile.txt 的 .txt 文件来跟踪我们的 Windows 服务,因此我们可以通过查看这个日志文件来测试我们的 Windows 服务的工作状况。

正如您在前面的屏幕中看到的,您可以在 TestWindowService 解决方案所在的物理位置找到 LogFile.txt 文件。

单击 LogFile.txt 以查看日志,我们的服务是否正在执行我们设置为每 30 秒执行一次的工作。

如果您查看前面的日志文件,我们可以证明我们的 Windows 服务正在运行,并且每隔 30 秒完成我们想要的工作。

停止 Windows 服务

要停止 Windows 服务,只需单击“服务”窗口中的“停止”链接,选择我们的 TestWindowService。

停止我们的服务后的日志文件:

在“VS2012的开发者命令提示符”中输入以下两条命令卸载TestWindowService.exe。

  1. cd <TestWindowService.exe 文件的物理位置>
    并按 Enter。就我而言,它是:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u “TestWindowService.exe”
    然后回车。
    执行上述命令后,TestWindowService 将从您的计算机中卸载。

概括

在本文中,我解释了如何开发 Windows 服务并在命令提示符下使用 InstallUtil.exe 安装它。

相信我已经把每一个步骤都解释的很清楚了,对于初学者开发和安装一个Windows服务来说是很容易理解的。


慕源网 » 使用 C# 开发和安装 Windows 服务

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录