C# Windows服务的创建、安装、调试

一、查看已有的Windows服务

选择菜单“开始”-〉“控制面板”-〉“管理工具”-〉“服务”来查看现有系统中的服务

 

二、C#中创建 Windows 服务

 

1、Visual Studio=> 新建 => 项目 => Windows 服务

 

 

2、重命名Service1.cs文件名为容易识别功能的文件名,这里我重命名成 MyFirstWinService.cs,如果类名改了,需要在 Program.cs文件的 Main() 方法里面的 new 对象也相应改过来

 

3、在此文件的设计视图中右键,在弹出的菜单中选择添加安装程序

 

 

4、项目会自动生成安装文件 ProjectInstaller.cs ,并且分别设置 serviceIntaller1 与 serviceProcessInstaller1 的属性。

 

 

 

 

5、到这里,服务的安装程序与框架已经搭建完毕

 

 

三、Windows服务的安装

 

1、新建安装服务的批处理文件

Install.bat

 
 
     
    

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest

 


2、新建卸载服务的批处理文件

Uninstall.bat

 
 
     
    

net stop ServiceTest
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe 

 

3、将批处理文件放入项目的bin->Debug文件夹下面,这样就可以方便使用程序控制服务的安装和卸载。

 

 

4、双击运行 Install.bat 进行自动安装 Windows 服务

 

5、安装成功后,可以进入Windows 服务 管理器,对刚才安装的服务设置启动方式:

 

新安装的服务一般是不会启动的,需要我们 点击上图中的启动按钮进行启动

 

 

四、Windows 服务开发过程中的调试

 

通过附加进程的方式调试Windows 服务,此方法必须先把写好的服务进行编译生成可执行的exe安装程序,并安装启动服务后,才可以进行附加此服务进程。

 

1、首先要对服务进行安装,然后启动服务。


2、打开VS项目,选择菜单 调试->附加到进程 选项,选择你的服务进程(如果找不到可以勾选 显示所有用户进程 选项)就可以了。如下图:

 

 

windows 服务实例:

每隔设置时间执行某段代码

internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new OrderUpdateService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

 

重点code:

using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;
using CRM.Services.Service;
using Castle.Windsor;
using Crm.DataSync.Installer;
using log4net;

public partial class OrderUpdateService : ServiceBase
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(OrderUpdateService));
        private static Timer _timer;
        private static bool _timerRunning;
        private static Timer _signTimer;
        private static bool _signTimerRunning;

        static readonly OrderUpdateNew Service = new OrderUpdateNew();

        public OrderUpdateService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Log.Info("service started");

                var container = new WindsorContainer();
                container.Install(new GlobalInstaller());

                var intervalStr = ConfigurationManager.AppSettings["Interval"];
                int interval = 60;
                int t;
                if (int.TryParse(intervalStr, out t))
                {
                    interval = t;
                }

                var period = interval * 60000;
                _timer = new Timer(timer_Elapsed);
                _timer.Change(2000, period);

                int mandatoryInterval = 5;
                intervalStr = ConfigurationManager.AppSettings["MandatoryInterval"];
                if (int.TryParse(intervalStr, out t))
                {
                    mandatoryInterval = t;
                }
                period = mandatoryInterval * 60000;
                _signTimer = new Timer(MandatorySignHandler);
                _signTimer.Change(2000, period);
            }
            catch (Exception ex)
            {
                Log.Error("", ex);
            }
        }

        protected override void OnStop()
        {
            try
            {
                Log.Info("service stopped");
            }
            catch (Exception ex)
            {
                Log.Error("", ex);
            }
        }

        void timer_Elapsed(object sender)
        {
            try
            {
                if (_timerRunning) return;
                _timerRunning = true;

                var service = Service;
                if (service != null && PassRules())
                {
                    service.UpdateData();
                }
                _timerRunning = false;
            }
            catch (Exception ex)
            {
                Log.Error("timer exception", ex);
            }

        }

        void MandatorySignHandler(object sender)
        {
            const string title = "客户确认签收订单处理";
            Log.Info(title + "begin");
            try
            {
                var service = Service;
                if (service != null)
                {
                    service.UpdateMandatorySignedOrder();
                }
            }
            catch (Exception ex)
            {
                Log.Error(title, ex);
            }
            Log.Info(title + "end");
        }

        bool PassRules()
        {
            var now = DateTime.Now;
            int hour = now.Hour;
            if (hour >= 0 && hour <= 5
                || (hour >= 22 && hour <= 24)) return false;
            return true;
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值