完成后立即重新运行方法

本文关键字:重新运行 方法 | 更新日期: 2023-09-27 18:31:04

现在我正在使用计时器来触发我的方法。但是,如何使服务在完成后立即运行我的方法呢?

private Timer timer;
    public Service()
    {
        InitializeComponent();
    }
    protected override void OnStart(string[] args)
    {
        DoSomething();
        timer = new Timer();
        timer.Enabled = true;
        timer.Interval = 60000;
        timer.AutoReset = true;
        timer.Start();
        timer.Elapsed += timer_Elapsed;
    }
    protected override void OnStop()
    {
        base.OnStop();
    }
    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        DoSomething();
    }

完成后立即重新运行方法

摆脱计时器并使用递归:

public Service()
{
  InitializeComponent();
  DoSomething();
}
private void DoSomething()
{
  // some code that takes a while to execute
  // make recursive call to self
  DoSomething();
}

编辑 接受的答案在服务的上下文中不起作用(实际上,它将执行,但服务本身将永远停留在"正在启动"状态,并会生成 1503 错误)。

下面是将持续执行方法的服务的完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace recursion
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        System.Threading.Thread thread;
        protected override void OnStart(string[] args)
        {
            System.IO.File.WriteAllText(@"C:'Temp'Foo.txt", "Starting at: " + System.DateTime.Now.ToString());
            thread = new System.Threading.Thread(DoSomething);
            thread.Name = "Worker Thread";
            thread.IsBackground = true;
            thread.Start();
        }
        private void DoSomething() {
            while (true)
            {
                System.IO.File.WriteAllText(@"C:'Temp'Foo.txt", "The Time is now: " + System.DateTime.Now.ToString());
                System.Threading.Thread.Sleep(1000);
            }
        }
        protected override void OnStop()
        {
        }
    }
}

@cslecours你错了,它会导致StackOverflow,但你是对的,因为导致OnStart方法不退出会导致Windows服务出错。

使用 Thread 和 infinite while 循环。

private void Start()
{
   while(true)
       DoSomething();
}
protected override void OnStart(string[] args)
{
   Task.Factory.StartNew(() => Start());
}