我创建了一个 C# windows 服务,它应该发送一些电子邮件,但是当我启动该服务时,我收到消息“本地服务启动然后停止”...“如果某些服务无法正常工作,则会自动停止做'
为什么会这样?
namespace EmailService
{
public partial class EmailService : ServiceBase
{
private System.Timers.Timer _timer = null;
private DateTime _lastRun = DateTime.Now;
private int _timerIntervalValue;
public EmailService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Timer"]))
{
throw new Exception("The timer value is not set in the app.config.");
}
else
{
_timerIntervalValue = Convert.ToInt32(ConfigurationManager.AppSettings["Timer"]);
}
_timer = new System.Timers.Timer(_timerIntervalValue);
_timer.Elapsed += OnTimedEvent;
_timer.Interval = Convert.ToInt32(_timerIntervalValue);
_timer.Enabled = true;
}
protected override void OnStop()
{
_timer.Stop();
_timer.Dispose();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Email email = new Email();
email.ProcessEmails();
_lastRun = DateTime.Now;
_timer.Start();
}
}
}
事件日志条目
服务无法启动。 System.Security.SecurityException: 未找到来源,但无法搜索到部分或所有事件日志。不可访问的日志:安全。 在 System.Diagnostics.EventLog.FindSourceRegistration(字符串源、字符串机器名、 bool 只读) 在 System.Diagnostics.EventLog.SourceExists(字符串源,字符串机器名) 在 System.Diagnostics.EventLog.SourceExists(字符串源)
最佳答案
您需要启动一个前台线程 以防止进程退出。
这只能通过创建新线程来实现。 请参阅下面的更新!Timer
作为后台线程工作。
在这里查看我的回答:
Best use of Windows Service for repeating a program call
这是一个非常简单的方法:
public partial class EmailService : ServiceBase
{
Thread _thread = new Thread(DoAlways)
protected override void OnStart(string[] args)
{
_thread.Start();
}
private void DoAlways()
{
while()
{
// ...
}
}
更新
System.Timers.Timer
类型的 Timer
使用 System.Threading.Timer
,后者又使用 native WIN32 计时器。
我确实在我的机器 (XP) 上编译并安装了您的服务,它运行良好。服务启动没有问题。我建议您对 interval 值进行硬编码以查看它是否有效,因为我怀疑它的值为零,因此计时器从未初始化。
关于无工作可做的 C# Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649442/