0

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

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

4

2 回答 2

3

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

您也可以从 C# Online查看这篇文章。它涵盖了一些想法,并包含文章的几个部分。 (注意;页面加载速度似乎有点慢,请耐心等待)

于 2008-10-29T14:21:39.007 回答
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函数小而快,否则你的服务将不会以服务没有及时响应的错误启动

希望这可以帮助

于 2008-10-30T10:39:49.750 回答