一、创建Windows服务

使用VS创建一个新的windows服务应用程序

创建完成之后

二、相关配置

修改Service1名称为StartService(可以不改,自行选择

添加安装程序并修改配置

安装完成之后,源码中会出现一个ProjectInstaller程序集,双击进入页面修改相关属性

              

   

添加文件夹和实体类

LogHelper.cs

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace WindowsService.Common
{
public class LogHelper
{
/// <summary>
/// 获取程序异常信息
/// </summary>
/// <param name="methodBase"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <returns></returns>
public static string GetExceptionMessage(MethodBase methodBase, Exception exception, string message)
{
string fullName = methodBase.ReflectedType.FullName;
string name = methodBase.Name;
string str = $"\r\n异常综合信息(类:{fullName};函数名称:{name};):\r\n";
str += "-----------\r\n";
str += ".Net异常信息:\r\n";
if (exception == null)
{
str += " 无异常对象,也无堆栈信息(exception == null)\r\n";
}
else
{
str += $" {exception.Message}\r\n";
str += $".Net堆栈信息:\r\n{exception.StackTrace}\r\n";
}
str += "-----------\r\n";
if (message != null && message.Trim().Length > )
{
str += "===========\r\n";
str += $"自定义信息:\r\n {message}\r\n";
str += "===========\r\n";
}
return str;
} /// <summary>
/// 写出日志信息 目录地址:string logPath = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
/// </summary>
/// <param name="folderName"></param>
/// <param name="message"></param>
public static void Write(string folderName, string message)
{
string text = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
if (folderName != null && folderName.Trim().Length > )
{
text += folderName;
}
WritingLogs(text, message);
} /// <summary>
/// 写出异常日志(.txt)
/// </summary>
/// <param name="strPath"></param>
/// <param name="strContent"></param>
public static void WritingLogs(string strPath, string strContent)
{
FileStream fileStream = null;
StreamWriter streamWriter = null;
try
{
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
strPath = string.Format("{0}\\{1}{2}", strPath, DateTime.Now.ToString("yyyy-MM-dd"), ".txt");
fileStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0L, SeekOrigin.End);
streamWriter.WriteLine(strContent + "\r\n\r\n--------------------------------------------------------" + DateTime.Now.ToString() + "--------------------------------------------------------\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
finally
{
streamWriter.Close();
fileStream.Close();
}
} }
}

LogHelper

Utility.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WindowsService.Common
{
public class Utility
{
/// <summary>
/// 是否到时间进行执行
/// </summary>
/// <param name="hour">当前时间(小时)</param>
/// <returns>true:时间已到;false:时间未到;</returns>
public static bool TimeOut(string hour)
{
string times = "14|20|01";
if (times == null || times.Trim().Length <= )
{
return false;
}
if (times.IndexOf('|') > )
{
foreach (string t in times.Split('|'))
{
if (t == hour)
{
return true;
}
}
}
else if (times == hour)
{
return true;
}
return false;
}
}
}

Utility

TaskStart.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsService.Common; namespace WindowsService.BusinessServices
{
public class TaskStart
{ /// <summary>
/// 业务开始运行
/// </summary>
public void TaskProcessing()
{
LogHelper.Write("Start", ".....服务正式运行.....");
Thread.Sleep( * * ); //在20秒内进行附加进程
try
{
bool isRun = false; //默认不执行
while (true)
{
string hour = DateTime.Now.ToString("HH"); //获得当前的时间
isRun = Utility.TimeOut(hour) ? true : false;
if (isRun)//判断服务是否运行
{
#region 具体业务 LogHelper.Write("具体业务", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, Guid.NewGuid().ToString())); #endregion isRun = false; //已经操作一次
Thread.Sleep( * * ); //休眠 62 分钟 //必须要超过 一个 小时
}
else
{
//睡眠两分钟
Thread.Sleep( * * ); //停止设定时间,精确度比Sleep高
}
}
}
catch (Exception ce)
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....服务异常.....\r\n\r\n")); ServiceController service = new ServiceController(new StartService().ServiceName);
service.Stop(); //停止服务
//service.Pause();//暂停服务
//service.Start();//开始服务
}
}
}
}

TaskStart(具体业务)

修改启动服务代码

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsService.BusinessServices;
using WindowsService.Common; namespace WindowsService
{
public partial class StartService : ServiceBase
{
/// <summary>
/// 当前服务是否停止(默认时flase)
/// </summary>
private bool isStop = false; /// <summary>
/// 启动服务
/// </summary>
public StartService()
{
InitializeComponent(); this.CanPauseAndContinue = true;
this.CanStop = true;
isStop = false;
} ///<summary>
///暂停服务
///</summary>
protected override void OnPause()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....暂停服务.....\r\n\r\n"));
isStop = true; //服务暂停
} ///<summary>
///恢复服务
///</summary>
protected override void OnContinue()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....继续服务.....\r\n\r\n"));
isStop = false; //继续服务
} /// <summary>
/// 服务停止
/// </summary>
protected override void OnStop()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....停止服务.....\r\n\r\n"));
isStop = true; //服务停止
} /// <summary>
/// 服务开始运行
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
try
{
//当服务没有停止时,开始具体业务
if (isStop == false)
{
Thread thread = new Thread(new ThreadStart(new TaskStart().TaskProcessing));
thread.Start();
}
}
catch (Exception ce)
{
LogHelper.Write("Error", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....停止服务.....\r\n\r\n"));
}
}
}
}

StartService

、服务安装

新建一个txt文本,输入以下内容,这里的WindowsService.exe 是程序路径,前面的路径是固定的,后面可变。修改txt文件名称为bat批处理文件,新建文本文档.txt——install.bat 。 然后右击 以管理员身份运行   这个批处理文件。这样服务就安装成功了。最后别忘记手动启动下这个服务。

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

、服务卸载

和服务安装步骤一样,输入以下内容。然后 以管理员身份运行 即可。

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

四、调试

源码地址:https://github.com/RainFate/WindowsServiceDemo/tree/master/WindowsService

C# Windows服务创建安装卸载的更多相关文章

  1. Windows服务的安装卸载及错误查找

    @echo off echo 清理原有服务项. . . %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil /U D:\abc\te ...

  2. WCF 下的windows服务的安装卸载

    安装:启动vs2010(如果是win2008要以管理员来启动)命令:installutil demo.exe 卸载:先在服务里停止这个服务,然后启动vs2010(如果是win2008要以管理员来启动) ...

  3. 通过批处理进行Windows服务的安装/卸载&启动/停止

    安装服务 @echo off set checked=2 set PATHS=%~sdp0 echo 按任意键执行安装……? pause>nul if %checked% EQU 2 ( %PA ...

  4. .net windows 服务创建、安装、卸载和调试

    原文:http://blog.csdn.net/angle860123/article/details/17375895 windows服务应用程序是一种长期运行在操作系统后台的程序,它对于服务器环境 ...

  5. Windows服务一:新建Windows服务、安装、卸载服务

    Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面 ...

  6. Windows服务创建及安装

    Windows服务创建及安装http://www.cnblogs.com/tuyile006/archive/2006/11/27/573654.html

  7. C#操作windows服务,安装、卸载、停止、启动

    public class ServiceUtil { private string _ServiceName = string.Empty; private string _AppName = str ...

  8. 使用InstallUtil对Windows服务进行安装与卸载

    关于Visual Studio 2012中使用InstallUtil对Windows服务进行安装与卸载的文章,在MSDN中的http://msdn.microsoft.com/en-us/librar ...

  9. windows服务创建与管理

    安装windows 服务 C:\Users\chensimin>cd \ C:\>cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 C:\W ...

随机推荐

  1. poj 2431 Expedition 贪心 优先队列 题解《挑战程序设计竞赛》

    地址 http://poj.org/problem?id=2431 题解 朴素想法就是dfs 经过该点的时候决定是否加油 中间加了一点剪枝 如果加油次数已经比已知最少的加油次数要大或者等于了 那么就剪 ...

  2. hashlib和hmac模块

    目录 一.hashlib模块 1.0.1 hash是什么 1.0.2 撞库破解hash算法加密 一.hashlib模块 1.0.1 hash是什么 hash是一种算法(Python3.版本里使用has ...

  3. 使用celery执行Django串行异步任务

    Django项目有一个耗时较长的update过程,希望在接到请求运行update过程的时候,Django应用仍能正常处理其他的请求,并且update过程要求不能并行,也不能漏掉任何一个请求 使用cel ...

  4. Netty - 粘包和半包(下)

    上一篇介绍了粘包和半包及其通用的解决方案,今天重点来看一下 Netty 是如何实现封装成帧(Framing)方案的. 解码核心流程 之前介绍过三种解码器FixedLengthFrameDecoder. ...

  5. sequelize时间自动格式化

    问题 每次查询datetime的字段,显示出来都是这种格式 2019-08-27T12:02:05.000Z 解决办法 初始化Sequelize的时候传入dialectOptions参数 let se ...

  6. 【IDEA】(2)---MAC代码模版

    IDEA(2)-MAC代码模版 IDEA提供了许多的自带代码模版,这些模版主要是对于我们经常开发用到的代码制作成一个模版,比如for循环,这个是经常会用到的代码,如果没有代码模版,我们需要一个一个手动 ...

  7. 使用 FiddlerCore 自定义 HTTP/HTTPS 网络代理

    Fiddler 是个很好用的网络请求查看与调试工具,还可以写插件来扩展其功能. Fiddler 插件开发,使用 WPF 作为 UI 控件 - J.晒太阳的猫 - 博客园 但部分场景下,需要自定义很多网 ...

  8. ASP.NET Core 使用 Redis 实现分布式缓存:Docker、IDistributedCache、StackExchangeRedis

    ASP.NET Core 使用 Redis 实现分布式缓存:Docker.IDistributedCache.StackExchangeRedis 前提:一台 Linux 服务器.已安装 Docker ...

  9. PHP mysqli_kill MySQLi 函数

    mysqli_kill - 让服务器杀掉一个 MySQL 线程 语法:mysqli_kill ( mysqli $link , int $processid ) 本函数可以用来让服务器杀掉 proce ...

  10. angular版聊天室|仿微信界面IM聊天|NG2+Node聊天实例

    一.项目介绍 运用angular+angular-cli+angular-router+ngrx/store+rxjs+webpack+node+wcPop等技术实现开发的仿微信angular版聊天室 ...