完成后重新运行方法

时间:2014-11-19 14:36:00

标签: c# windows-services

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

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();
    }

2 个答案:

答案 0 :(得分:1)

摆脱计时器并使用递归:

public Service()
{
  InitializeComponent();
  DoSomething();
}

private void DoSomething()
{
  // some code that takes a while to execute

  // make recursive call to self
  DoSomething();
}

编辑接受的答案不会在服务环境中发挥作用(实际上,它会执行,但服务本身将永远停留在' Starting&#39 ;状态,并将生成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服务错误。

答案 1 :(得分:1)

使用Thread和无限循环。

private void Start()
{
   while(true)
       DoSomething();
}

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