[英]Timer not firing in Windows Service but fires when in a console app
我正在尝试在 Windows 服务中使用计时器,我安装了该服务并在服务中启动它,但计时器不会触发。 但是,当我在控制台应用程序中使用完全相同的代码时,计时器会触发。 我尝试了很多不同的建议,但在 Windows 服务中似乎没有一个对我有用
这是我的代码...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.IO;
namespace NextService
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer aTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(aTimer_Elapsed);
aTimer.Enabled = true;
aTimer.AutoReset = true;
aTimer.Start();
}
private static void aTimer_Elapsed(object sender, ElapsedEventArgs e)
{
string path = @"c:\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome" + DateTime.Now.ToString());
}
}
//throw new NotImplementedException();
}
protected override void OnStop()
{
}
}
}
我只是不明白为什么它可以在控制台应用程序中运行,而不是在此服务中运行。 我只是让它在火灾事件上创建一个文件进行测试,然后再将我的代码放入其中。
谢谢
使用线程计时器更新代码
protected override void OnStart(string[] args)
{
TimerCallback callback = aTimer_Elapsed;
Timer timer = new Timer(callback);
timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(10));
Thread.Sleep(10000);
}
private void aTimer_Elapsed(object state)
{
string path = @"c:\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome" + DateTime.Now.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.