Windows服务的漂亮代码模板

时间:2008-10-29 13:56:03

标签: windows-services

任何指向Windows服务的良好模板的链接? (寻找C#代码)

具有我可以扩展的基本功能的东西。

2 个答案:

答案 0 :(得分:3)

你要找的东西有点清楚。 Visual Studio中的 Windows服务项目类型创建一个项目,其中包含使用基本Windows服务所需的模板。

您还可以从C#Online查看this article。它涉及一些想法,并有一些文章的部分。 (注意;页面似乎加载有点慢,所以请耐心等待)

答案 1 :(得分:1)

我使用VS2005,我喜欢从基本模板开始。

将Service类修改为此

using System;
using System.ServiceProcess;
using System.Timers;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        //better is to read from settings or config file
        private readonly Double _interval = (new TimeSpan(1, 0, 0, 0)).TotalMilliseconds;
        private Timer m_Timer;

        public Service1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            m_Timer = new Timer();
            m_Timer.BeginInit();
            m_Timer.AutoReset = false;
            m_Timer.Enabled = true;
            m_Timer.Interval = 1000.0;
            m_Timer.Elapsed += m_Timer_Elapsed;
            m_Timer.EndInit();
        }

        private void m_Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //TODO WORK WORK WORK
            RestartTimer();
        }

        private void RestartTimer()
        {
            m_Timer.Interval = _interval;
            m_Timer.Start();
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            Start();
        }

        protected override void OnStop()
        {
            Stop();
            base.OnStop();
        }

        public void Start()
        {
            m_Timer.Start();
        }

        public new void Stop()
        {
            m_Timer.Stop();
        }
    }
}

在添加安装程序后使用InstallUtil.exe进行安装:http://msdn.microsoft.com/en-us/library/ddhy0byf(VS.80).aspx

保持Init功能小而快,否则您的服务不会以服务未及时响应的错误开始

希望这有帮助