c# - Windows 服务的后台 worker

标签 c# windows-services

我正在使用 C# 在 Visual Studio 2010 中创建 Windows 服务,我有一些方法,例如 AddMultiply 和其他方法,我将它们放在 onStart 方法。现在,我希望这些方法每五分钟运行一次。那么后台工作进程如何帮助我呢?

protected override void OnStart(string[] args)
{
    add(); // yes, it doesn't have parameters      
}

最佳答案

计时器是正确的方法。我有一个稍微增强的版本,负责在 OnStop 方法中关闭计时器。

在您的 program.cs 中,我将执行以下操作以简化调试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace SampleWinSvc
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
#if (!DEBUG)
      ServiceBase[] ServicesToRun;
      ServicesToRun = new ServiceBase[] { new Service1() };
      ServiceBase.Run(ServicesToRun);
#else
      //Debug code: this allows the process to run 
      // as a non-service. It will kick off the
      // service start point, and then run the 
      // sleep loop below.
      Service1 service = new Service1();
      service.Start();
      // Break execution and set done to true to run Stop()
      bool done = false;
      while (!done)
        Thread.Sleep(10000);
      service.Stop();
#endif
    }
  }
}

然后,在您的 Service1.cs 代码中:

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

namespace SampleWinSvc
{
    public partial class Service1 : ServiceBase
    {
        /// <summary>
        /// This timer willl run the process at the interval specified (currently 10 seconds) once enabled
        /// </summary>
        Timer timer = new Timer(10000);

        public Service1()
        {
            InitializeComponent();
        }

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

        public void Start()
        {
            // point the timer elapsed to the handler
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            // turn on the timer
            timer.Enabled = true;
        }

        /// <summary>
        /// This is called when the service is being stopped. 
            /// You need to wrap up pretty quickly or ask for an extension.
        /// </summary>
        protected override void OnStop()
        {
            timer.Enabled = false;
        }

            /// <summary>
            /// Runs each time the timer has elapsed. 
            /// Remember that if the OnStop turns off the timer, 
            /// that does not guarantee that your process has completed. 
            /// If the process is long and iterative, 
            /// you may want to add in a check inside it 
            /// to see if timer.Enabled has been set to false, or 
            /// provide some other way to check so that 
            /// the process will stop what it is doing.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            MyFunction();
        }

        private int secondsElapsed = 0;
        void MyFunction()
        {
            secondsElapsed += 10;
        }
    }
}

通过在编译选项中设置#DEBUG var,您可以自己运行代码 作为一个程序然后当你准备好测试你的关闭逻辑时,简单地打破所有并 设置完成为真。多年来我一直在使用这种方法并取得了很大的成功。

如代码中所述,如果您在计时器事件中做任何冗长的事情,那么您可能希望从 OnStop 对其进行监视,以确保它在事情中间关闭时有足够的时间。

关于c# - Windows 服务的后台 worker ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10754689/

相关文章:

c# - 在C#中执行代码之前如何获得最大值?

c# - HttpClient 正在发送额外的 cookie

windows-services - 使用 pscp.exe 时跳过主机检查

asp.net-mvc - MVC SignalR 服务器和 Windows 服务 SIignalR 客户端之间的 SignalR

c# - 机器中的多任务与多进程

c# - Visual Studio 使用 MVC 5 和 Razor 突出显示 .cshtml 页面中不存在的错误

c# - 在单个测试类中测试接口(interface)的多个实现

c# - Azure Blob 和表存储以更简单的方式重写代码

azure - 创建 blob 后立即将 Azure blob 复制到本地计算机

asp.net-core - 如何更改 Visual Studio 2017 中用于调试的默认浏览器?