-Begin-

大家好!我是付工。
在实际工作中,如果我们需要开发一个运行在后台,无需用户交互,不需要界面的应用程序,我们可以通过Windows服务来实现。
本文主要介绍如何基于C#创建一个Windows服务,来实现西门子PLC的定时读取保存。

Windows服务说明

Windows 服务是一种特殊类型的应用程序,能够在系统启动时自动运行,且无需用户登录即可执行。

它适合于以下场景:

  • 持续运行的任务(如日志采集、网络代理等)

  • 系统后台维护(如自动更新、性能监控)

  • 需要在无人值守环境中执行的任务

Windows 服务的核心特性:

  • 通过服务控制管理器(SCM) 管理

  • 运行时与用户登录状态无关

  • 支持系统启动时自动运行

Windows服务创建

1、创建一个新项目,项目模板选择Windows服务(.Net Framework)

2、项目名称为WindowsServiceDemo,项目创建完成后如下:

3、修改服务名称为SiemensPLCService:

4在设计界面的空白处,右击弹窗中,选择添加安装程序

5点击添加安装程序之后,会自动添加一个ProjectInstaller界面,里面有两个组件,分别是serviceProcessInstaller和serviceInstaller。

6、选择serviceInstaller,在右侧的属性进行设置,主要可以设置以下属性:

无需界面,自动化运行:C#实现西门子PLC数据定时读取与保存
  • ServiceName:服务名称

  • Description:服务描述

  • StartType:启动类型

7、接着选择ProjectInstaller进行设置,主要设置Account,指示用来运行此服务的账户类型,可以设置为LocalSystem。

8、设置完成之后,切换到SiemensPLCService这个类,点击切换到代码视图,我们可以看到后台有一些自动生成的代码

public partial class SiemensPLCService : ServiceBase{    public SiemensPLCService()    {        InitializeComponent();    }    protected override void OnStart(string[] args)    {    }    protected override void OnStop()    {    }}

我们可以在OnStart和OnStop里写一些代码逻辑。

9、写了一个简单的逻辑,就是每次服务启动或停止都会向指定的文件中写入一串信息。

private Plc siemens;private CancellationTokenSource cts;protected override void OnStart(string[] args){    try    {        this.siemens = new Plc(CpuType.S7200Smart, '192.168.2.150'00);        this.siemens.Open();
        cts = new CancellationTokenSource();        Task.Run(async () =>        {            while (!cts.IsCancellationRequested)            {                try                {                    uint temp = Convert.ToUInt32(this.siemens.Read('DB1.DBD4'));                    float val = temp.ConvertToFloat();                    await Task.Delay(1000);                    WriteInfo('读取PLC数据:'+val.ToString('f2'));                }                catch (Exception ex)                {                    WriteInfo(ex.Message);                }            }            this.siemens.Close();        });
    }    catch (Exception ex)    {        WriteInfo(ex.Message);    }}private string filePath = @'D:ServiceLog.txt';private void WriteInfo(string info){    using (FileStream stream = new FileStream(filePath, FileMode.Append))    {        using (StreamWriter writer = new StreamWriter(stream))        {            writer.WriteLine($'{DateTime.Now},{info}');        }    }}protected override void OnStop(){    this.siemens?.Close();}

Windows服务安装卸载

我们直接运行刚刚创建的服务,发现是无法运行的,提示如下:

接下来,我们使用这个exe来进行安装和卸载Windows服务。

1、首先,使用管理员权限打开cmd命令行,然后进入这个路径下,便于直接操作InstallUtil。

cd C:WindowsMicrosoft.NETFrameworkv4.0.30319

2、安装服务命令:installutil  exe绝对路径 ;
installutil C:UsersAdministratorDesktopWindowsServiceDemoWindowsServiceDemobinDebugWindowsServiceDemo.exe

打开服务,可以看到TestService这个名称的服务已经安装完成,

3、安装完成后,双击打开,可以启动服务,也可以手动停止:

4、观察D盘文件,可以看到PLC的数据每秒会存一次到指定文件中:

5、需要卸载服务时,可以执行卸载服务命令:installutil  exe绝对路径 -u ;
installutil C:UsersAdministratorDesktopWindowsServiceDemoWindowsServiceDemobinDebugWindowsServiceDemo.exe -u

写在最后

去年8月,历经2年,我出版了一本上位机书籍——《C#上位机开发实战指南》。

#artContent h1{font-size:16px;font-weight: 400;}#artContent p img{float:none !important;}#artContent table{width:100% !important;}