在實(shí)際工作中,如果我們需要開發(fā)一個(gè)運(yùn)行在后臺(tái),無需用戶交互,不需要界面的應(yīng)用程序,我們可以通過Windows服務(wù)來實(shí)現(xiàn)。本文主要介紹如何基于C#創(chuàng)建一個(gè)Windows服務(wù),來實(shí)現(xiàn)西門子PLC的定時(shí)讀取保存。
Windows 服務(wù)是一種特殊類型的應(yīng)用程序,能夠在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行,且無需用戶登錄即可執(zhí)行。
它適合于以下場景:
持續(xù)運(yùn)行的任務(wù)(如日志采集、網(wǎng)絡(luò)代理等)
系統(tǒng)后臺(tái)維護(hù)(如自動(dòng)更新、性能監(jiān)控)
需要在無人值守環(huán)境中執(zhí)行的任務(wù)
Windows 服務(wù)的核心特性:
1、創(chuàng)建一個(gè)新項(xiàng)目,項(xiàng)目模板選擇Windows服務(wù)(.Net Framework):
2、項(xiàng)目名稱為WindowsServiceDemo,項(xiàng)目創(chuàng)建完成后如下:
3、修改服務(wù)名稱為SiemensPLCService:
4、在設(shè)計(jì)界面的空白處,右擊彈窗中,選擇添加安裝程序:

5、點(diǎn)擊添加安裝程序之后,會(huì)自動(dòng)添加一個(gè)ProjectInstaller界面,里面有兩個(gè)組件,分別是serviceProcessInstaller和serviceInstaller。
6、選擇serviceInstaller,在右側(cè)的屬性進(jìn)行設(shè)置,主要可以設(shè)置以下屬性:
ServiceName:服務(wù)名稱
Description:服務(wù)描述
StartType:啟動(dòng)類型
7、接著選擇ProjectInstaller進(jìn)行設(shè)置,主要設(shè)置Account,指示用來運(yùn)行此服務(wù)的賬戶類型,可以設(shè)置為LocalSystem。
8、設(shè)置完成之后,切換到SiemensPLCService這個(gè)類,點(diǎn)擊切換到代碼視圖,我們可以看到后臺(tái)有一些自動(dòng)生成的代碼:
public partial class SiemensPLCService : ServiceBase
{
public SiemensPLCService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
我們可以在OnStart和OnStop里寫一些代碼邏輯。
9、寫了一個(gè)簡單的邏輯,就是每次服務(wù)啟動(dòng)或停止都會(huì)向指定的文件中寫入一串信息。
private Plc siemens;
private CancellationTokenSource cts;
protected override void OnStart(string[] args)
{
try
{
this.siemens = new Plc(CpuType.S7200Smart, "192.168.2.150", 0, 0);
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數(shù)據(jù):"+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();
}
我們直接運(yùn)行剛剛創(chuàng)建的服務(wù),發(fā)現(xiàn)是無法運(yùn)行的,提示如下:
?接下來,我們使用這個(gè)exe來進(jìn)行安裝和卸載Windows服務(wù)。
1、首先,使用管理員權(quán)限打開cmd命令行,然后進(jìn)入這個(gè)路徑下,便于直接操作InstallUtil。
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
2、安裝服務(wù)命令:installutil exe絕對(duì)路徑 ;installutil C:\Users\Administrator\Desktop\WindowsServiceDemo\WindowsServiceDemo\bin\Debug\WindowsServiceDemo.exe
打開服務(wù),可以看到TestService這個(gè)名稱的服務(wù)已經(jīng)安裝完成,
3、安裝完成后,雙擊打開,可以啟動(dòng)服務(wù),也可以手動(dòng)停止:
4、觀察D盤文件,可以看到PLC的數(shù)據(jù)每秒會(huì)存一次到指定文件中:
5、需要卸載服務(wù)時(shí),可以執(zhí)行卸載服務(wù)命令:installutil exe絕對(duì)路徑 -u ;installutil C:\Users\Administrator\Desktop\WindowsServiceDemo\WindowsServiceDemo\bin\Debug\WindowsServiceDemo.exe -u
閱讀原文:原文鏈接
該文章在 2025/3/21 10:29:47 編輯過