c#编写windows服务

一、创建一个Windows Service

1)创建Windows Service项目

2)对Service重命名

将Service1重命名为你服务名称,这里我们命名为ServiceTest。

二、创建服务安装程序

1)添加安装程序

之后我们可以看到上图,自动为我们创建了ProjectInstaller.cs以及2个安装的组件。 也可以用代码创建这些

2)修改安装服务名

右键serviceInsraller1,选择属性,将ServiceName的值改为ServiceTest。

3)修改安装权限

右键serviceProcessInsraller1,选择属性,将Account的值改为LocalSystem。

三、写入服务代码

1)打开ServiceTest代码

右键ServiceTest,选择查看代码。

2)写入Service逻辑

添加如下代码:

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

namespace WindowsServiceTest
{
	public partial class ServiceTest : ServiceBase
	{
		public ServiceTest()
		{
			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.");
			}
		}
	}
}

这里我们的逻辑很简单,启动服务的时候写个日志,关闭的时候再写个日志。


四:安装和卸载windows服务

    其实不用那么麻烦,

    安装:步骤:win+R -----CMD  -------输入microsoft的framework的相应版本的执行程序位置(如:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe   空一格再输入你的服务的执行文件的路径(如:D:\zt_documents\服务\SSY.DealerLoginStateService.root\SSY.DealerLoginStateService\SSY.LoginStateService\SSY.LoginStateService\bin\Debug\XX.exe(这里的.exe写自己的项目的名称) 

   卸载:步骤:win+R -----CMD  -------输入microsoft的framework的相应版本的执行程序位置(如:C:\Windows\Microsoft.net\Framework\v4.0.30319\InstallUtil.exe  -u   空一格再输入你的服务的执行文件的路径(如:D:\zt_documents\服务\SSY.DealerLoginStateService.root\SSY.DealerLoginStateService\SSY.LoginStateService\SSY.LoginStateService\bin\Debug\XX.exe(这里的.exe写自己的项目的名称) 

   如果出现安装有问题,提示权限问题,或者InstallUtil.exe不是有些的win32程序,直接把可以安装目录下面的复杂过去就可以安装了

     


五:服务定时任务小例子

[csharp]  view plain  copy
  1. partial class GetUnitePService : ServiceBase  
  2.    {  
  3.        public GetUnitePService()  
  4.        {  
  5.            InitializeComponent();  
  6.        }  
  7.   
  8.        Timer t;  
  9.        protected override void OnStart(string[] args)  
  10.        {  
  11.            t = new Timer();  
  12.            t.Interval = 5*60 * 1000;  
  13.            t.Elapsed += t_Elapsed;  
  14.            t.Start();  
  15.            WriteToLog("开始服务");  
  16.        }  
  17.   
  18.        void t_Elapsed(object sender, ElapsedEventArgs e)  
  19.        {  
  20.            WriteToLog("开始执行一次获取," + DateTime.Now);  
  21.        }  
  22.   
  23.        protected override void OnStop()  
  24.        {  
  25.            t.Stop();  
  26.            WriteToLog("停止服务");  
  27.        }  
  28.   
  29.        private void getUnitePrice()  
  30.        {  
  31.            GetPriceSvc.GetPriceSvcClient gpc = new GetPriceSvc.GetPriceSvcClient();  
  32.            GetPriceSvc.ReturnDataOfArrayOfPriceInfo_DTODhuO2YUv res = gpc.GetPriceInfoByCompany("3ma5c094-7d4c-4f8c-8e8f-3530f18ca8kc""fygjGetUnitePrice");  
  33.            WriteToLog("获取完了得到的条数:" + res.Value.Count() + " ," + DateTime.Now);  
  34.        }  
  35.   
  36.   
  37.        private void WriteToLog(string str)  
  38.        {  
  39.            try  
  40.            {  
  41.                string strdt = DateTime.Now.ToString("yyyy-MM-dd");  
  42.                FileStream aFile = new FileStream("D:\\LogGetUnitePrice\\" + strdt + ".txt", FileMode.Append);  
  43.                StreamWriter sw = new StreamWriter(aFile, Encoding.Default);  
  44.                sw.WriteLine(str);  
  45.                sw.Close();  
  46.            }  
  47.            catch { }  
  48.        }  
  49.    }  

六:后台设置服务名称,可以写在配置文件中读取

       或者直接在安装的时候从命名即可

[csharp]  view plain  copy
  1. [RunInstaller(true)]  
  2.    public partial class ProjectInstaller : System.Configuration.Install.Installer  
  3.    {  
  4.        private System.ServiceProcess.ServiceInstaller serviceInstaller1;  
  5.        private ServiceProcessInstaller processInstaller;  
  6.        public ProjectInstaller()  
  7.        {  
  8.            InitializeComponent();  
  9.   
  10.            processInstaller = new ServiceProcessInstaller();  
  11.            serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();  
  12.            processInstaller.Account = ServiceAccount.LocalService;  
  13.            serviceInstaller1.StartType = ServiceStartMode.Automatic;//自动启动  
  14.            serviceInstaller1.ServiceName = "xkAutoAdvert";  
  15.            serviceInstaller1.Description = "讯酷网广告统计消息队列处理服务";  
  16.            Installers.Add(serviceInstaller1);  
  17.            Installers.Add(processInstaller);  
  18.        }  
  19.   
  20.   
  21.    } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值