没有工作要做的C#Windows服务

本文关键字:C#Windows 服务 工作 | 更新日期: 2023-09-27 17:50:11

我创建了一个C#窗口服务,该服务应该发送一些电子邮件,但当我启动该服务时,我收到消息"本地服务启动,然后停止"…'如果没有工作要做,一些服务会自动停止

为什么会这样?

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(字符串源,字符串machineName,布尔只读(位于System.Diagnostics.EventLog.SourceExists(字符串源,字符串machineName(在System.Diagnostics.EventLog.SourceExists(字符串源(

没有工作要做的C#Windows服务

您需要启动前台线程以阻止进程退出。

这只能通过创建新线程来实现 Timer用作后台线程 请参阅下面的更新!

请点击此处查看我的答案:

最佳使用Windows服务重复程序调用


这是一种非常简单的方法:

public partial class EmailService : ServiceBase
{
    Thread _thread = new Thread(DoAlways)

     protected override void OnStart(string[] args)
     {
        _thread.Start();
     }
     private void DoAlways()
     {
        while()
        {
           // ...
        }
     }

更新

类型为CCD_ 3的CCD_ 2使用CCD_。

我确实在我的机器(XP(上编译并安装了您的服务,它只是起了作用。服务启动时没有问题。我建议您对间隔值进行硬编码,看看它是否有效,因为我怀疑它的值为零,因此计时器从未初始化。

查看系统事件日志(事件查看器(。我确信发生了一些错误,这就是您的服务自动停止的原因。

可能的问题是您的服务找不到您的app.config(请确保其名称为yoursvcname.exe.config(。为了进行测试,请尝试将您的配置文件放在"C:''WINDOWS''system32''"中。

编辑

通过看到您的事件日志错误,我认为您正试图从代码中访问事件日志,但您没有所需的权限,或者由于某种原因无法访问指定的事件日志源。

编辑2

或者看看以下答案:写入事件日志时出现System.Security.SecurityException

(授予NetworkService对EventLog/Security密钥的读取权限(