关于windows服务

偶尔会遇到这种情况:服务需要一个无限制的循环。这样的话就会出现,服务启动有问题,启动到最后会报错。

于是:可以尝试使用线程来运行

我使用了Log4记录异常。来防止出现异常导致服务停止的情况。

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

namespace NetEasyNewsServer
{
    partial class NetEasyService : ServiceBase
    {
        public NetEasyService()
        {
            InitializeComponent();
        }
        bool mark = true;
        Thread thread;
        protected override void OnStart(string[] args)
        {
            mark = true;
            thread = new Thread(Main);
            thread.Start();
            // TODO: 在此处添加代码以启动服务。
        }
        /// <summary>
        /// 程序线程
        /// </summary>
        void Main()
        {
            while (mark)
            {
                int sleeptime = 0;
                try
                {
                    sleeptime = Int32.Parse(ConfigurationManager.AppSettings["SleepTime"]);
                }
                catch (Exception exc)
                {
                    Pub.LogHelp.Logger.Fatal("sleepTime config error :" + exc.Message);
                    sleeptime = 3600000;
                }
                try
                {
                    using (GeterOnStart start = new GeterOnStart())
                    {
                        start.NetEasyInsert();
                    }
                }
                catch (Exception exc)
                {
                    Pub.LogHelp.Logger.Fatal("Main run error :" + exc.Message);
                }

                Thread.Sleep(sleeptime);
            }
        }
        /// <summary>
        /// 暂停
        /// </summary>
        protected override void OnPause()
        {
            base.OnPause();
        }
        /// <summary>
        /// 继续
        /// </summary>
        protected override void OnContinue()
        {
            base.OnContinue();
        }
        protected override void OnStop()
        {
            mark = false;
            thread.Abort();
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }
    }
}

在Onstop事件中,终止了线程。

开发完成了之后。就是安装了。

首先。要为服务添加安装程序

1.

一定要记得调整安装设计器的属性哦。设置Account:

2.接下来就是安装了。

本人开发使用的4.0框架。安装的时候使用4.0的命令

使用cmd命令。当然,如果你是win7系统的话,记得使用管理员身份启动哦。

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  C:\aa\bb\bin\xxxx.exe(xxxx.exe是我的服务程序的名称)

至于卸载的时候 后面加个/u就可以啦

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  C:\aa\bb\bin\xxxx.exe /u

原文地址:https://www.cnblogs.com/QQ544952425/p/2595684.html