C# 方法完成后立即重新运行该方法
现在我正在使用计时器来触发我的方法。但是,如何使服务在完成后立即运行我的方法C# 方法完成后立即重新运行该方法,c#,windows-services,C#,Windows Services,现在我正在使用计时器来触发我的方法。但是,如何使服务在完成后立即运行我的方法 private Timer timer; public Service() { InitializeComponent(); } protected override void OnStart(string[] args) { DoSomething(); timer = new Timer(); timer.E
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您错误地认为它会导致堆栈溢出,但您正确地认为,导致OnStart方法不退出将导致Windows服务出错。使用线程和无限while循环
private void Start()
{
while(true)
DoSomething();
}
protected override void OnStart(string[] args)
{
Task.Factory.StartNew(() => Start());
}
@哈比卜,你读过我的问题了吗?我不想用定时器。我想在完成某个部分后立即重新运行它。我错过了该部分。从内部调用您的方法,使其递归。不确定这是否是一个好方法。另外,在递归调用方法之前,请确保您有一些条件,否则最终会出现StackOverflow异常。按照措辞,OP希望知道如何“在方法完成后”再次执行该方法。如果该方法只执行类似Console.WriteLine(“Boo!”)的操作,您是对的,它不会像现在这样是一个非常有用的程序。当我使我的方法递归时,我在启动服务时会出现错误1053…但是这个过程是启动的,我知道这听起来很轻率,但是如果你想在DoSomething()完成后再次运行,只需再次调用它就可以了不?许多编程语言的发明者都这么认为。不要这样做,它将导致一个
StackOverflowException
,因为您永远不会从函数返回。您的示例和我的示例的不同之处在于您启动一个新线程以持续运行该方法。如果他只想运行这个方法,并在它完成后继续运行它(正如他在问题中所说的),那么这两种方法都可以很好地工作。你是在暗示递归——几乎每种现代编程语言的基本主食——是危险的,不可使用吗?@GojiraDeMonstah递归如果不是无限的,就可以了。在您的情况下,堆栈溢出最终会发生。使用包含Console.WriteLine调用和自身调用的更快的DoSomething进行尝试。问题是(我是否发现)我从未退出OnStart,这就是我无法启动windows GUI服务的原因