WindowsService,比较浅显的理解就是放于后台跑的应用程序,像我们PC,其实都跑着很多后台程序,我们可能都不知道,因此我认为这是对于一些经常性重复性处理,用它非常合适,比如从数据库不断写数据,写个应用放于桌面上跑,一不小心还可能被关掉,安全性美观性都会大大降低。
在写服务的时候不可避免的入过某些坑,对于一些定时性处理任务,我觉得用服务不如用Windows自带的任务计划程序,可以选择启动的时间点,循环的周期,Windows10在所用应用里面的Windows管理工具里面,具体用法也很简单,别忘记添加.exe。
(一)创建
新建项目——Windows——Windows服务。在解决方案资源管理器中找到窗体设计文件*.cs,做如下操作:
添加安装程序后会出现,ProjectInstaller.cs会出现两个服务安装器,如下:
我们对上面1号进行配置,在属性窗口中修改服务账户类型Account账户类型LocalSystem;2号配置服务名字和描述,启动类型为自动,这样每次开机就能启动服务了。
进行到这里服务已经创建成功,现在我们在里面写内容:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
}
}
protected override void OnStop()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
sw.Close();
}
}
protected override void OnPause()
{
//服务暂停执行代码
base.OnPause();
}
protected override void OnContinue()
{
//服务恢复执行代码
base.OnContinue();
}
protected override void OnShutdown()
{
//系统即将关闭执行代码
base.OnShutdown();
}
}
服务写好了,我们需要把它注册到PC中,我们可以选择cmd敲命令,也可以用脚本安装,出于程序化考虑,我用的是脚本.bat,但无论哪种,我们都需要使用微软提供的安装器InstallUtil.exe。
//Install.bat
cd C:
cd C:\Users\Pc-Yang\Desktop\AutoWindowsService\AtuoWindowsService\ServiceClient\bin\Service
installutil.exe AtuoWindowsService.exe
Net Start WinServer
pause
//Uninstall.bat
cd C:
cd C:\Users\Pc-Yang\Desktop\AutoWindowsService\AtuoWindowsService\ServiceClient\bin\Service
InstallUtil.exe /u AtuoWindowsService.exe
pause
(二)调用
我用的是本地客户端调用,当然Web网页也能调。我写了4个按钮如下,分别为:安装、启动、停止、卸载服务,其实还有暂停和恢复,跟启动停止区别应该是否退出进程,有兴趣的可以去深挖一下。
,我们再看看几块代码功能:
//生成上面安装/卸载脚本
private void Form1_Load(object sender, EventArgs e)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\Service\\Install.bat", false))
{
sw.WriteLine("cd "+System.Environment.CurrentDirectory.Substring(0, 2));
sw.WriteLine("cd "+System.Environment.CurrentDirectory + "\\Service");
sw.WriteLine("installutil.exe AtuoWindowsService.exe");
sw.WriteLine("Net Start WinServer");
sw.WriteLine("pause");
}
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\Service\\Uninstall.bat", false))
{
sw.WriteLine("cd " + System.Environment.CurrentDirectory.Substring(0, 2));
sw.WriteLine("cd "+System.Environment.CurrentDirectory+"\\Service");
sw.WriteLine("InstallUtil.exe /u AtuoWindowsService.exe");
sw.WriteLine("pause");
}
}
//安装服务
private void setup_Click(object sender, EventArgs e)
{
try
{
if (CheckServiceExist())
{
MessageBox.Show("服务已存在,安装失败!");
return;
}
else
{
string CurrentDirectory = System.Environment.CurrentDirectory;
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = CurrentDirectory + "\\Service\\Install.bat"; ;
process.StartInfo.CreateNoWindow = true;
process.Start();
MessageBox.Show("服务安装成功,已启动!");
process.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
//卸载服务
private void Uinstal_Click(object sender, EventArgs e)
{
try
{
if(CheckServiceExist())
{
string CurrentDirectory = System.Environment.CurrentDirectory;
System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "Uninstall.bat";
process.StartInfo.CreateNoWindow = true;
process.Start();
MessageBox.Show("服务已卸载完毕!");
process.Close();
}
else
{
MessageBox.Show("不存在需删除的服务,卸载无效!");
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
//恢复服务
private void startup_Click(object sender, EventArgs e)
{
//服务恢复执行代码
try
{
if (CheckServiceExist())
{
ServiceController serviceController = new ServiceController("WinServer");
if (serviceController.Status == ServiceControllerStatus.Running)
{
MessageBox.Show("服务已经开启,无效操作!");
return;
}
else
{
serviceController.Refresh();
serviceController.Start();
MessageBox.Show("服务启动成功!");
}
}
else
{
MessageBox.Show("不存在服务,请先安装!");
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
//停止服务
private void stop_Click(object sender, EventArgs e)
{
//服务暂停执行代码
try
{
if (CheckServiceExist())
{
ServiceController serviceController = new ServiceController("WinServer");
if (serviceController.Status == ServiceControllerStatus.Stopped)
{
MessageBox.Show("服务已经停止,无效操作!");
return;
}
else
{
if (serviceController.CanStop) { serviceController.Refresh(); serviceController.Stop(); };
MessageBox.Show("服务停止成功!");
}
}
else
{
MessageBox.Show("不存在服务,请先安装!");
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
总结
1.调试WindowsService服务我们可以借助事件查看器的错误来帮助甄判服务的一些操作错误。
2.安装和卸载(即Install.bat和Uninstall.bat)都需要管理员权限才能正确安装,那么我们调用程序一定要是管理员权限运行,可以通过给项目添加应用程序清单文件,修改里面的level为 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,程序运行就是以管理员权限。