我有一个大约10分钟内执行的方法。它本身就很顺利。我需要每小时使用Windows服务启动此方法(这是必须的)。所以我通过一些例子编写了我的服务(只需一次启动):
partial class ServiceWSDRun : ServiceBase
{
protected override void OnStart(string[] args)
{
Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
t.Start();
}
}
现在当我安装它时,它会在一个新线程中启动我的方法,但是这个线程似乎以OnStart()结束 - 它实际上从我的方法开始记录了一些信息。为什么它会停止,我该怎么办?
我想最后我应该有这样的事情:
partial class ServiceWSDRun : ServiceBase
{
System.Timers.Timer timer = null;
protected override void OnStart(string[] args)
{
Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
t.Start();
timer = new System.Timers.Timer();
timer.Interval = 60 * 60 * 1000; // 1 hour
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
timer.Enabled = true;
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
WebServiceDownload.MainProgram.Execute();
}
protected override void OnStop()
{
timer.Enabled = false;
}
}
如何让它发挥作用?请记住,该方法需要大约10分钟才能执行。
答案 0 :(得分:2)
您应该使用System.Threading.Timer而不是System.Timers.Timer。
以下是对此的参考:
https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
另外,关于同一主题的另一个主题是:
System.Timers.Timer vs System.Threading.Timer
您应该锁定执行,避免在第一次执行完成之前执行第二次执行。